Skip to content

Commit 1acede5

Browse files
committed
add solution: best-time-to-buy-and-sell-stock
1 parent cb5c505 commit 1acede5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
# 121. Best Time to Buy and Sell Stock
3+
4+
use **bottom-up dynamic programming** to solve the problem.
5+
6+
## Time and Space Complexity
7+
```
8+
TC: O(n)
9+
SC: O(1)
10+
```
11+
12+
## TC is O(n):
13+
- iterating through the list just once to find the maximum profit. = O(n)
14+
15+
## SC is O(1):
16+
- using two variables to store the minimum price and maximum profit. = O(1)
17+
'''
18+
class Solution:
19+
def maxProfit(self, prices: List[int]) -> int:
20+
if len(prices) == 1:
21+
return 0
22+
23+
lowest_price = prices[0] # SC: O(1)
24+
max_profit = 0 # SC: O(1)
25+
26+
for price in prices: # TC: O(n)
27+
lowest_price = min(price, lowest_price)
28+
curr_profit = price - lowest_price
29+
max_profit = max(curr_profit, max_profit)
30+
31+
return max_profit

0 commit comments

Comments
 (0)