Skip to content

Commit 3b61bc7

Browse files
authored
Update Best Time to Buy and Sell Stock - Leetcode 121.py
1 parent 6dab404 commit 3b61bc7

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,23 @@ def maxProfit(self, prices: List[int]) -> int:
3131
max_profit = profit
3232

3333
return max_profit
34+
35+
36+
# Optimal Solution for Bootcamp
37+
class Solution:
38+
def maxProfit(self, prices: List[int]) -> int:
39+
# Time: O(n)
40+
# Space: O(1)
41+
min_price = float('inf')
42+
max_profit = 0
43+
44+
for price in prices:
45+
profit = price - min_price
46+
47+
if price < min_price:
48+
min_price = price
49+
50+
if profit > max_profit:
51+
max_profit = profit
52+
53+
return max_profit

0 commit comments

Comments
 (0)