第九章 动态规划(十二)
主要内容
股票问题
动态规划题目
309.最佳买卖股票时机含冷冻期
代码
class Solution:
# dp[i]的状态:
# 买入状态:状态0 = ① 前一天就为买入状态, ②今天买入 (前一天状态1,前一天状态3)
# dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i], dp[i-1][3] - prices[i])
# 卖出状态:状态1 = 前两天就卖出了,今天度过冷冻期 (前一天就是状态1,前一天是状态3)
# 状态2 = 今天卖出
# dp[i][1] = max(dp[i-1][1], dp[i-1][3])
# dp[i][2] = dp[i-1][0] + prices[i]
# 冷冻状态:状态3 = 今天冷冻期
# dp[i][3] = dp[i-1][2]
# 初始化
# dp[0][0] = -prices[0], dp[0][i] = 0
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
dp = [[0] * 4 for _ in range(n)]
dp[0][0] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i], dp[i-1][3] - prices[i])
dp[i][1] = max(dp[i-1][1], dp[i-1][3])
dp[i][2] = dp[i - 1][0] + prices[i]
dp[i][3] = dp[i - 1][2]
return max(dp[-1][:])
309.最佳买卖股票时机含冷冻期
代码
class Solution:
# 卖出时交手续费
# dp[i][0] 是买入状态 = (前一天买入,当天买入)
# dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i])
# dp[i][1] 是卖出状态 = (前一天卖出状态,当天卖出)
# dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i] - fee)
# 初始化
# dp[0][0] = -prices[0]
# dp[0][1] = 0
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
dp = [[0] * 2 for _ in range(n)]
dp[0][0] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee)
return max(dp[-1][:])