Skip to content

Commit 6ca4a28

Browse files
committed
Solved "Best Time to Buy and Sell Stock"
1 parent 091227d commit 6ca4a28

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,29 @@
1+
"""
2+
Constraints:
3+
1. 1 <= prices.length <= 10^5
4+
2. 0 <= prices[i] <= 10^4
5+
6+
Time Complexity: O(n)
7+
8+
Space Complexity: O(1)
9+
10+
ํ’€์ด ๋ฐฉ๋ฒ•:
11+
- ๋ฐฐ์—ด์„ ํ•œ ๋ฒˆ ์ˆœํšŒํ•˜๋ฉด์„œ:
12+
1. ํ˜„์žฌ๊นŒ์ง€์˜ ์ตœ์†Œ ๊ฐ€๊ฒฉ(min_price)์„ ๊ณ„์† ๊ฐฑ์‹ 
13+
2. ํ˜„์žฌ ๊ฐ€๊ฒฉ์—์„œ ์ตœ์†Œ ๊ฐ€๊ฒฉ์„ ๋บ€ ๊ฐ’(ํ˜„์žฌ ๊ฐ€๋Šฅํ•œ ์ด์ต)๊ณผ ๊ธฐ์กด ์ตœ๋Œ€ ์ด์ต์„ ๋น„๊ตํ•˜์—ฌ ๋” ํฐ ๊ฐ’์„ ์ €์žฅ
14+
- ์ด ๋ฐฉ์‹์œผ๋กœ ๊ฐ ์‹œ์ ์—์„œ ๊ฐ€๋Šฅํ•œ ์ตœ๋Œ€ ์ด์ต์„ ๊ณ„์‚ฐํ•จ
15+
16+
To Do:
17+
- ๋‹ค๋ฅธ ์ ‘๊ทผ ๋ฐฉ๋ฒ• ์ฐพ์•„๋ณด๊ธฐ (Two Pointers, Dynamic Programming)
18+
"""
19+
class Solution:
20+
def maxProfit(self, prices: List[int]) -> int:
21+
min_price = prices[0]
22+
max_profit = 0
23+
24+
for i in range(1, len(prices)):
25+
min_price = min(min_price, prices[i])
26+
max_profit = max(max_profit, prices[i] - min_price)
27+
28+
return max_profit
129

0 commit comments

Comments
ย (0)