Skip to content

Commit b74daeb

Browse files
committed
best time to buy and cell stock solution
1 parent 75ace28 commit b74daeb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def maxProfit(self, prices: List[int]) -> int:
3+
# profit: μ΅œλŒ€ 이읡
4+
profit = 0
5+
6+
# current_minimum: ν˜„μž¬κΉŒμ§€μ˜ μ΅œμ†Œ 가격
7+
current_minimum = prices[0]
8+
9+
# current_profit: ν˜„μž¬κΉŒμ§€μ˜ μ΅œλŒ€ 이읡
10+
current_profit = 0
11+
12+
# 전체 λ°°μ—΄μ—μ„œ μ΅œμ†Ÿκ°’κ³Ό, μ΅œμ†Ÿκ°’ 인덱슀 이후 μ΅œλŒ“κ°’μ„ 이읡으둜 κ³„μ‚°ν•˜λŠ” 반볡문
13+
for i in range(1, len(prices)):
14+
# 이읡이 λ°œμƒν•  경우 ν˜„μž¬ 이읡 κ°±μ‹ 
15+
# ν˜„μž¬ 이읡을 κ°±μ‹ ν•  λ•Œλ§ˆλ‹€ μ§€κΈˆκΉŒμ§€μ˜ μ΅œλŒ€ 이읡도 κ°±μ‹ 
16+
if prices[i] > current_minimum:
17+
current_profit = max(current_profit, prices[i] - current_minimum)
18+
profit = max(profit, current_profit)
19+
# 이읡이 λ°œμƒν•˜μ§€ μ•Šμ„ 경우 μ΅œμ†Ÿκ°’ κ°±μ‹ 
20+
else:
21+
current_minimum = prices[i]
22+
23+
# μ΅œλŒ€ 이읡만 μ €μž₯λ˜μ–΄ λ°˜ν™˜
24+
return profit

0 commit comments

Comments
Β (0)