Skip to content

Commit 478d56d

Browse files
committed
[7th batch] week 5 - best time to buy and sell stock
1 parent 8a4a45d commit 478d56d

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

โ€Žbest-time-to-buy-and-sell-stock/liza0525.pyโ€Ž

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,25 @@ def maxProfit(self, prices: List[int]) -> int:
2323

2424
# ์ตœ์ข…์ ์œผ๋กœ ๊ธฐ๋ก๋œ max_profit์ด ๋‹ต
2525
return max_profit
26+
27+
28+
# 7๊ธฐ ํ’€์ด
29+
# ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
30+
# - prices์˜ ๊ธธ์ด n๋งŒํผ ์ˆœํšŒ
31+
# ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
32+
# - ์ƒ์ˆ˜๋งŒ ์‚ฌ์šฉ
33+
class Solution:
34+
# ์ฒซ๋‚ ๋ถ€ํ„ฐ ๋งค์ผ์˜ ๊ฐ€๊ฒฉ์ด ์ตœ์†Œ์ธ์ง€, ์ตœ๋Œ€์ธ์ง€๋ฅผ ํŒ๋‹จํ•˜์—ฌ ๊ฐ€์žฅ ํฐ ์ด์ต์„ ๋‚ผ ์ˆ˜ ์žˆ๋Š” ๊ฐ’์„ ๊ณ„์‚ฐํ•œ๋‹ค.
35+
# ์ฒซ๋‚ ๋ถ€ํ„ฐ ์‹œ๊ฐ„ ์ˆœ์„œ๋Œ€๋กœ ํ™•์ธํ•ด์•ผ ํ•จ(๊ธฐ๊ฐ„ ์ค‘ ๊ฐ€์žฅ ์ตœ๋Œ“๊ฐ’์ด ๊ฐ€์žฅ ์ตœ์†Ÿ๊ฐ’๋ณด๋‹ค ๋น ๋ฅผ ์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ)
36+
def maxProfit(self, prices: List[int]) -> int:
37+
min_sell_price = 10 ** 4 # ๋ฌธ์ œ ์กฐ๊ฑด์—์„œ 10์˜ 4์Šน์ด ์ตœ๋Œ€๋ผ๊ณ  ํ•˜์—ฌ ์ด๋ฅผ min_sell_price์˜ ์ดˆ๊ธฐ๊ฐ’์œผ๋กœ
38+
max_profit = 0
39+
40+
for price in prices:
41+
# ๋งค์ผ ์ˆœํšŒํ•˜๋ฉฐ ์ง€๋‚˜๊ฐ„ ์‹œ๊ฐ„๋“ค ์ค‘์— ๊ฐ€์žฅ ์ž‘์€ price์ธ์ง€ ํ™•์ธํ•˜์—ฌ ์—…๋ฐ์ดํŠธ
42+
min_sell_price = min(min_sell_price, price)
43+
44+
# ๋งค์ผ ์ˆœํšŒํ•˜๋ฉฐ ์˜ค๋Š˜ ์–ป์„ ์ˆ˜ ์žˆ๋Š” profit๊ณผ ์ด์ „์— ์–ป์—ˆ๋˜ max_profit์„ ๋น„๊ตํ•˜์—ฌ ์—…๋ฐ์ดํŠธ
45+
max_profit = max(max_profit, price - min_sell_price)
46+
47+
return max_profit

0 commit comments

Comments
ย (0)