LeetCode121题 买卖股票的最佳时机
只能买1次
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# dp[0]代表持有股票时最大收益,dp[1]代表不持有股票最大收益
dp = [-prices[0], 0]
for i in range(1, len(prices)):
dp[0], dp[1] = max(dp[0], -prices[i]), max(dp[1], dp[0] + prices[i])
return dp[1]
LeetCode122题 买卖股票的最佳时机II
能买无数次,相对只能买1次,主要变化在dp[0]的递推公式
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# dp[0]代表持有股票时最大收益,dp[1]代表不持有股票最大收益
dp = [-prices[0], 0]
for i in range(1, len(prices)):
dp[0], dp[1] = max(dp[0], dp[1] - prices[i]), max(dp[1], dp[0] + prices[i])
return dp[1]
LeetCode188题 买卖股票的最佳时机IV
只能买k次,需要记录2*k个状态
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
# dp[2 * i]代表第i+1次持有股票(买入),dp[2 * i + 1]代表第i+1次不持有股票(卖出)
# 初始化时,假设可以当天买卖
dp = [0] * (2 * k)
for i in range(k):
dp[2 * i] = -prices[0]
for i in range(1, len(prices)):
for j in range(k):
if j == 0:
# 第一次买入
dp[2 * j] = max(dp[2 * j], -prices[i])
else:
dp[2 * j] = max(dp[2 * j], dp[2 * j - 1] - prices[i])
dp[2 * j + 1] = max(dp[2 * j + 1], dp[2 * j] + prices[i])
return dp[-1]
LeetCode309题 买卖股票的最佳时机含冷冻期
能买无数次,与“买卖股票的最佳时机II”的区别:由于有冷冻期,所以买入股票时需要以dp[i - 2][1]的状态买股票,分析:
- 情况1:第i天是冷静期,不能以dp[i-1][1]购买股票,所以以dp[i - 2][1]买股票
- 情况2:第i天不是冷静期,理论上应该以dp[i-1][1]购买股票,但是第i天不是冷静期说明,第i-1天没有卖出股票,则dp[i-1][1]=dp[i-2][1],所以可以用dp[i-2][1]买股票
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 1:
return 0
# 二维DP数组转移(下面实现优化为1维,只记录最近两个状态)
# dp[i][0] = max(dp[i-1][0], dp[i-2][1] - price[i])
# dp[i][1] = max(dp[i-1][1], dp[i-1][0] + price[i])
dp = [[-prices[0], 0],
[max(-prices[0], -prices[1]), max(0, prices[1] - prices[0])]]
for i in range(2, len(prices)):
dp[0][0], dp[0][1], dp[1][0], dp[1][1] = \
dp[1][0], dp[1][1], max(dp[1][0], dp[0][1] - prices[i]), max(dp[1][1], dp[1][0] + prices[i])
return dp[1][1]
LeetCode714题 买卖股票的最佳时机含手续费
能买无数次,与“买卖股票的最佳时机II”的区别:由于有手续费,所以卖出股票时需要添加手续费
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
dp = [-prices[0], 0]
for i in range(1, len(prices)):
dp[0], dp[1] = max(dp[0], dp[1] - prices[i]), max(dp[1], dp[0] + prices[i] - fee)
return dp[1]