From 465edb9f15c3779d1b18b7e781ad65ffc9b6542a Mon Sep 17 00:00:00 2001 From: Rochak <24rochak@gmail.com> Date: Fri, 26 Jul 2019 11:58:19 +0530 Subject: [PATCH] Best time to buy and sell stock --- Best Time to Buy and Sell Stock.py | 16 ++++++++++++++++ Maximum subarray.py | 14 ++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 Best Time to Buy and Sell Stock.py create mode 100644 Maximum subarray.py diff --git a/Best Time to Buy and Sell Stock.py b/Best Time to Buy and Sell Stock.py new file mode 100644 index 0000000..93f074d --- /dev/null +++ b/Best Time to Buy and Sell Stock.py @@ -0,0 +1,16 @@ +def maxProfit(prices: [int]) -> int: + import sys + profit = 0 + minprice = sys.maxsize + for i in range(0, len(prices)): + if prices[i] < minprice: + minprice = prices[i] + elif prices[i] - minprice > profit: + profit = prices[i] - minprice + + return profit + + +l = [3, 2, 6, 5, 0, 3] +ans = maxProfit(l) +print(ans) diff --git a/Maximum subarray.py b/Maximum subarray.py new file mode 100644 index 0000000..5c445a2 --- /dev/null +++ b/Maximum subarray.py @@ -0,0 +1,14 @@ +def maxSubArray(nums: [int]) -> int: + tot = nums[0] + for i in range(1, len(nums)): + nums[i] = max(nums[i - 1], 0) + nums[i] + if nums[i] > tot: + tot = nums[i] + + return tot + + +l = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + +ans = maxSubArray(l) +print(ans)