【leetcode】动态规划刷题tricks-买卖股票问题

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]

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值