diff --git a/Best Time to Buy and Sell Stock IV.py b/Best Time to Buy and Sell Stock IV.py new file mode 100644 index 0000000..ed23ad2 --- /dev/null +++ b/Best Time to Buy and Sell Stock IV.py @@ -0,0 +1,28 @@ +class Solution: + def maxProfit(self, k: int, prices: List[int]) -> int: + + + if not prices: + return 0 + + + if k>=len(prices)//2: + ans = 0 + for i in range(1,len(prices)): + ans += max(0,prices[i]-prices[i-1]) + return ans + + + cost = [float("inf") for i in range(k+1)] + profit = [0 for i in range((k+1))] + + for price in prices: + for i in range(1,(k+1)): + cost[i] = min(cost[i], price-profit[i-1]) + profit[i] = max(profit[i], price-cost[i]) + + + return profit[-1] + +Time: NK +Space: O(K) diff --git a/Best Time to Buy and Sell Stock-I.py b/Best Time to Buy and Sell Stock-I.py new file mode 100644 index 0000000..c049900 --- /dev/null +++ b/Best Time to Buy and Sell Stock-I.py @@ -0,0 +1,14 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + profit = 0 + lowSoFar = 1000000 + for i in range(len(prices)): + + lowSoFar = min(lowSoFar, prices[i]) + profit = max(profit, prices[i]-lowSoFar) + + return profit + + +Time: O(N) +Space: O(1) diff --git a/Best Time to Buy and Sell Stock-II.py b/Best Time to Buy and Sell Stock-II.py new file mode 100644 index 0000000..4252569 --- /dev/null +++ b/Best Time to Buy and Sell Stock-II.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + sum = 0 + for i in range(1,len(prices)): + + sum += max(0, prices[i]-prices[i-1]) + + return sum +Time: O(N) +Space: O(1) diff --git a/Best Time to Buy and Sell Stock-III.py b/Best Time to Buy and Sell Stock-III.py new file mode 100644 index 0000000..7308f28 --- /dev/null +++ b/Best Time to Buy and Sell Stock-III.py @@ -0,0 +1,22 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + firstCost = float("inf") + secondCost = float("inf") + + firstProfit = 0 + secondProfit = 0 + + + for cost in prices: + + firstCost = min(firstCost, cost) + + firstProfit = max(firstProfit, cost-firstCost) + + secondCost = min(secondCost, cost-firstProfit) + + secondProfit = max(secondProfit, cost-secondCost) + + return secondProfit +Time: O(N) +Space: O(1)