Skip to content

Commit abcd4ee

Browse files
committed
add solution: best-time-to-buy-and-sell-stock
1 parent d63b4b7 commit abcd4ee

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'''
2+
๋ฌธ์ œ: ํ•œ๋ฒˆ์˜ ๊ตฌ๋งค์™€ ํŒ๋งค๋กœ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ์ด์ต์„ ๊ตฌํ•˜๋ผ.
3+
ํ’€์ด: ์ฃผ์–ด์ง„ ๊ฐ€๊ฒฉ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ์ตœ์ €๊ฐ€์™€ ์ตœ๊ณ ๊ฐ€๋ฅผ ๊ฐฑ์‹ ํ•˜๋ฉฐ ์ตœ๋Œ€ ์ด์ต์„ ๊ณ„์‚ฐํ•œ๋‹ค.
4+
์ตœ์ €๊ฐ€๋Š” ํ˜„์žฌ ์ตœ์ €๊ฐ€๊ฒฉ๋ณด๋‹ค ๋‚ฎ์€ ๊ฐ€๊ฒฉ์ด ๋‚˜์˜ค๋ฉด ๊ฐฑ์‹ ํ•˜๊ณ ,
5+
์ตœ๊ณ ๊ฐ€๋Š” ํ˜„์žฌ ์ตœ๊ณ ๊ฐ€๊ฒฉ๋ณด๋‹ค ๋†’์€ ๊ฐ€๊ฒฉ์ด ๋‚˜์˜ค๋ฉด ๊ฐฑ์‹ ๋ฐ ์ •๋‹ต์ธ์ง€ ๋น„๊ตํ•œ๋‹ค.
6+
์‹œ๊ฐ„๋ณต์žก๋„: O(n)
7+
๊ณต๊ฐ„๋ณต์žก๋„: O(1)
8+
9+
'''
10+
11+
12+
class Solution:
13+
def maxProfit(self, prices: List[int]) -> int:
14+
ma, mi = prices[0], prices[0]
15+
answ = 0
16+
for i in range(1, len(prices)):
17+
if mi > prices[i]:
18+
mi, ma = prices[i], prices[i]
19+
if ma < prices[i]:
20+
ma = prices[i]
21+
answ = max(answ, ma-mi)
22+
return answ

0 commit comments

Comments
ย (0)