Skip to content

Commit f49eefa

Browse files
authored
Update buy_sell_stock.py
1 parent 3d53941 commit f49eefa

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

dp/buy_sell_stock.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,21 @@
2020
"""
2121

2222

23-
def max_profit(prices):
23+
# O(n^2) time
24+
def max_profit_naive(prices):
25+
"""
26+
:type prices: List[int]
27+
:rtype: int
28+
"""
29+
max_so_far = 0
30+
for i in range(0, len(prices) - 1):
31+
for j in range(i + 1, len(prices)):
32+
max_so_far = max(max_so_far, prices[j] - prices[i])
33+
return max_so_far
34+
35+
36+
# O(n) time
37+
def max_profit_optimized(prices):
2438
"""
2539
input: [7, 1, 5, 3, 6, 4]
2640
diff : [X,-6, 4,-2, 3,-2]
@@ -29,7 +43,6 @@ def max_profit(prices):
2943
"""
3044
cur_max, max_so_far = 0, 0
3145
for i in range(1, len(prices)):
32-
for j in range(i, len(prices))
33-
cur_max = max(0, prices[j] - prices[i])
46+
cur_max = max(0, cur_max + prices[i] - prices[i-1])
3447
max_so_far = max(max_so_far, cur_max)
3548
return max_so_far

0 commit comments

Comments
 (0)