File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments