File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ # ์๊ฐ ๋ณต์ก๋: O(n)
2+ # - prices ๋ฐฐ์ด์ ํ ๋ฒ๋ง ์ํํ๋๋ก ํจ
3+
4+ # ๊ณต๊ฐ ๋ณต์ก๋: O(1)
5+ # - ์์ ์์ฃผ๋ก๋ง ์ฌ์ฉ
6+
7+ class Solution :
8+ # ์ฒซ ๋ ์ดํ ๊ฐ๊ฒฉ๋ค์ ์ํํ๋ฉด์, ํ์ฌ ๊ฐ๊ฒฉ์ผ๋ก ํ๋ฉด ์ผ๋ง๋ ์์ต๋๋์ง ๊ณ์ฐํ๊ณ
9+ # ์ต์ ๋งค์๊ฐ(min_price)๋ฅผ ๊ฐฑ์ ํ๋ฉฐ ๋งค์ ๊ฐ๊ฒฉ์ ์ต์ํํ๋ค.
10+ def maxProfit (self , prices : List [int ]) -> int :
11+ max_profit = 0 # ์ง๊ธ๊น์ง ์ป์ ์ ์์๋ ์ต๋ ์์ต
12+ min_price = prices [0 ] # ์ง๊ธ๊น์ง ๋์จ ๊ฐ๊ฒฉ ์ค ๊ฐ์ฅ ๋ฎ์ ๊ฐ(์ต์ ์ ๋งค์ ์์ )
13+
14+ for current_price in prices [1 :]:
15+ # ํ์ฌ ์์ ์์ ํ๋ฉด ์ป์ ์ ์๋ ์์ต
16+ profit = current_price - min_price
17+
18+ # ์ง๊ธ๊น์ง ๋ณธ ์์ต ์ค ๊ฐ์ฅ ํฐ ๊ฐ์ผ๋ก ์
๋ฐ์ดํธ
19+ max_profit = max (max_profit , profit )
20+
21+ # ์ต์ ๋งค์ ๊ฐ๊ฒฉ ๊ฐฑ์ (๋ ๋ฎ์ ๊ฐ๊ฒฉ์ด ๋์ค๋ฉด ๋ฐ๊ฟ์ค๋ค)
22+ min_price = min (min_price , current_price )
23+
24+ # ์ต์ข
์ ์ผ๋ก ๊ธฐ๋ก๋ max_profit์ด ๋ต
25+ return max_profit
You canโt perform that action at this time.
0 commit comments