Skip to content

Commit 4ca1ba9

Browse files
committed
feat: [Week 05-1] solve best-time-to-buy-and-sell-stock
1 parent fa4a499 commit 4ca1ba9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Solution: 1) 2중 포문을 돌면서 max값을 구한다.
3+
Time: O(n^2)
4+
Space: O(1)
5+
6+
Time Limit Exceeded
7+
8+
"""
9+
10+
11+
class Solution:
12+
def maxProfit(self, prices: List[int]) -> int:
13+
result = 0
14+
for l in range(len(prices) - 1):
15+
for r in range(l + 1, len(prices)):
16+
result = max(result, prices[r] - prices[l])
17+
18+
return result
19+
20+
21+
"""
22+
Solution:
23+
1) prices를 순회하면서 max_profit 을 찾는다.
24+
2) profit 은 current price - min_profit로 구한다.
25+
Time: O(n)
26+
Space: O(1)
27+
"""
28+
29+
30+
class Solution:
31+
def maxProfit(self, prices: List[int]) -> int:
32+
n = len(prices)
33+
max_profit = 0
34+
min_price = prices[0]
35+
36+
for i in range(1, len(prices)):
37+
profit = prices[i] - min_price
38+
max_profit = max(max_profit, profit)
39+
min_price = min(prices[i], min_price)
40+
return max_profit

0 commit comments

Comments
 (0)