Skip to content

Commit 4531d7b

Browse files
committed
week 5 - best time to buy and sell stock
1 parent 807a383 commit 4531d7b

File tree

1 file changed

+25
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)