File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
2+
3+ from typing import List
4+
5+ class Solution :
6+ def maxProfit1 (self , prices : List [int ]) -> int :
7+ """
8+ [Complexity]
9+ - TC: O(n)
10+ - SC: O(1)
11+
12+ [Approach]
13+ prices๋ฅผ ์ํํ๋ฉด์ ๋ค์์ ํธ๋ํนํ๋ฉด ๋๋ค.
14+ (1) ์ง๊ธ๊น์ง์ ์ต์ ๊ฐ๊ฒฉ์ธ min_price ํธ๋ํน: min(min_price, price)
15+ (2) ์ง๊ธ๊น์ง์ ์ต๋ ์์ต์ธ max_profit ํธ๋ํน: max(max_profit, price - min_price)
16+ """
17+ max_profit , min_price = 0 , prices [0 ]
18+
19+ for price in prices :
20+ min_price = min (min_price , price )
21+ max_profit = max (max_profit , price - min_price )
22+
23+ return max_profit
24+
25+ def maxProfit (self , prices : List [int ]) -> int :
26+ """
27+ [Complexity]
28+ - TC: O(n)
29+ - SC: O(1)
30+
31+ [Approach]
32+ two-pointer(buy, sell)๋ก๋ ์ ๊ทผ ๊ฐ๋ฅํ๋ค.
33+ ๋ ๊ฐ์ pointer buy์ sell์ 0, 1 ์ธ๋ฑ์ค์์ ์์ํ ํ, sell์ ์์ง์ฌ๊ฐ๋ฉฐ curr_profit = prices[sell] - prices[buy]๋ฅผ ๊ตฌํ๋ค.
34+ ๊ทธ๋ฆฌ๊ณ curr_profit์ด 0๋ณด๋ค ํฌ๋ฉด max_profit์ ํธ๋ํนํ๊ณ , ๊ทธ๋ ์ง ์์ผ๋ฉด buy๋ฅผ sell ์์น๋ก ๋น๊ธด๋ค.
35+ (curr_profit์ด 0๋ณด๋ค ํฌ์ง ์๋ค๋ ๊ฒ์, buy ์์ ์ price ์ดํ์ธ price๊ฐ sell ์์ ์์ ๋ฐ๊ฒฌ๋์๋ค๋ ๋ป์ด๋ค!)
36+ """
37+ buy , sell = 0 , 1
38+ max_profit = 0
39+
40+ while sell < len (prices ):
41+ curr_profit = prices [sell ] - prices [buy ]
42+ if curr_profit > 0 :
43+ max_profit = max (max_profit , curr_profit )
44+ else :
45+ buy = sell
46+ sell += 1
47+
48+ return max_profit
You canโt perform that action at this time.
0 commit comments