Skip to content

Commit 0703dff

Browse files
committed
feat: Add Solution to #221 Best Time to Buy And Sell Stock
1 parent 11bcf09 commit 0703dff

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution(object):
2+
def maxProfit(self, prices):
3+
"""
4+
:type prices: List[int]
5+
:rtype: int
6+
์ฃผ์–ด์ง„ prices๋ฅผ ํ•œ ๋ฒˆ๋งŒ ์ˆœํšŒํ•˜๋ฉด์„œ
7+
์ง€๊ธˆ๊นŒ์ง€์˜ ์ตœ์†Ÿ๊ฐ’์„ ์ถ”์ ํ•˜๊ณ ,
8+
'ํ˜„์žฌ ๊ฐ€๊ฒฉ - ์ง€๊ธˆ๊นŒ์ง€์˜ ์ตœ์†Ÿ๊ฐ’'์œผ๋กœ ๊ณ„์‚ฐ๋˜๋Š” ์ด์ต์ด
9+
'์ง€๊ธˆ๊นŒ์ง€์˜ ์ตœ๋Œ€ ์ด์ต(์ดˆ๊ธฐ 0)๋ณด๋‹ค ํฌ๋ฉด ๊ฐฑ์‹ ํ•˜์—ฌ
10+
์ตœ์ข… ์ตœ๋Œ€ ์ด์ต ๊ตฌํ•˜๊ธฐ ๋ฌธ์ œ
11+
Time Complexity: O(n)
12+
Space Complexity: O(1)
13+
"""
14+
max_profit = 0 # ์ด์ต์ด ์—†์„ ๋•Œ 0์„ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ์ดˆ๊ธฐํ™”
15+
min_price = float('inf') # ์ตœ์†Œ ๊ฐ€๊ฒฉ ์ €์žฅ, ๋ฌดํ•œ๋Œ€๋กœ ์ดˆ๊ธฐํ™”ํ•ด์„œ ๋ฃจํ”„ ์ฒซ ๋ฒˆ์งธ ๊ฐ€๊ฒฉ๋ถ€ํ„ฐ ์ตœ์†Œ ๊ฐ€๊ฒฉ์— ์ €์žฅ
16+
17+
for price in prices:
18+
# ์ตœ๋Œ€ ์ด์ต ๊ฐฑ์‹ 
19+
max_profit = max(max_profit, (price - min_price))
20+
# ์ตœ์†Œ ๊ฐ€๊ฒฉ ๊ฐฑ์‹ 
21+
min_price = min(min_price, price)
22+
# ์ตœ์†Œ ์ด์ต ๊ฐฑ์‹  ์ดํ›„ ์ตœ์†Œ ๊ฐ€๊ฒฉ ๊ฐฑ์‹ ํ•ด์•ผ ํ•จ
23+
# ์ตœ๋Œ€ ์ด์ต ์ž์ฒด๋Š” ์ด๋ฏธ '์‚ฐ' ์ฃผ์‹์— ๋Œ€ํ•ด ๊ณ„์‚ฐํ•ด์•ผ ํ•˜๋ฏ€๋กœ
24+
# ์‚ฌ๋Š” ๋™์‹œ ํŒ” ์ˆ˜ ์—†์Œ
25+
26+
return max_profit

0 commit comments

Comments
ย (0)