Skip to content

Commit c82a79d

Browse files
committed
121. 买卖股票的最佳时机
1 parent 584dd73 commit c82a79d

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

dp/121_maxProfit.py

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,66 @@
22

33

44
class Solution:
5+
def maxProfit_1(self, prices: List[int]) -> int:
6+
if not prices:
7+
return 0
8+
max_profit = 0
9+
for i in range(len(prices)):
10+
for j in range(i + 1, len(prices)):
11+
max_profit = max(max_profit, prices[j] - prices[i])
12+
return max_profit
13+
14+
def maxProfit_dp(self, prices: List[int]) -> int:
15+
if not prices:
16+
return 0
17+
n = len(prices)
18+
# 创建两个数组,一个记录每次卖出的最大收益,一个记录每次买入最大收益
19+
buy = [0] * n
20+
sell = [0] * n
21+
buy[0] = -prices[0]
22+
for i in range(1, n):
23+
# 第i天卖出收益 = max(第i - 1天卖出收益,第i - 1天买入收益 + 当天股价)
24+
sell[i] = max(sell[i - 1], buy[i - 1] + prices[i])
25+
# 第i天买入收益 = max(第i - 1天买入收益,-当天股价)
26+
buy[i] = max(buy[i - 1], -prices[i])
27+
return sell[-1]
28+
29+
def maxProfit_dp_1(self, prices: List[int]) -> int:
30+
if not prices:
31+
return 0
32+
n = len(prices)
33+
dp = [[0 for _ in range(2)] for _ in range(n)]
34+
dp[0][0] = 0
35+
dp[0][1] = -prices[0]
36+
for i in range(1, n):
37+
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])
38+
dp[i][1] = max(dp[i - 1][1], -prices[i])
39+
return dp[-1][0]
40+
41+
def maxProfit_dp_2(self, prices: List[int]) -> int:
42+
if not prices:
43+
return 0
44+
45+
n = len(prices)
46+
sell = 0
47+
buy = -prices[0]
48+
for i in range(1, n):
49+
sell = max(sell, buy + prices[i])
50+
buy = max(buy, -prices[i])
51+
return sell
52+
53+
def maxProfit_greed(self, prices: List[int]) -> int:
54+
if not prices:
55+
return 0
56+
n = len(prices)
57+
min_price = prices[0]
58+
max_profit = 0
59+
for i in range(1, n):
60+
max_profit = max(max_profit, prices[i] - min_price)
61+
min_price = min(min_price, prices[i])
62+
return max_profit
63+
64+
# =============================================
565
def maxProfit(self, prices: List[int]) -> int:
666
if not prices:
767
return 0
@@ -42,4 +102,4 @@ def maxProfit_better(self, prices: List[int]) -> int:
42102
if __name__ == '__main__':
43103
prices = [7, 1, 5, 3, 6, 4]
44104
solution = Solution()
45-
print(solution.maxProfit_better(prices))
105+
print(solution.maxProfit_greed(prices))

0 commit comments

Comments
 (0)