Skip to content

Commit b909f60

Browse files
committed
solve(w05): 121. Best Time to Buy and Sell Stock
1 parent 00739f9 commit b909f60

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

0 commit comments

Comments
ย (0)