Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Best Time to Buy and Sell Stock IV.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions Best Time to Buy and Sell Stock-I.py
Original file line number Diff line number Diff line change
@@ -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)
10 changes: 10 additions & 0 deletions Best Time to Buy and Sell Stock-II.py
Original file line number Diff line number Diff line change
@@ -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)
22 changes: 22 additions & 0 deletions Best Time to Buy and Sell Stock-III.py
Original file line number Diff line number Diff line change
@@ -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)