188. 买卖股票的最佳时机 IV

  1. [题目链接](188. 买卖股票的最佳时机 IV - 力扣(LeetCode))

  2. 解题思路:来到i位置,决定买或者不卖,动态规划,直接加dp表即可。

    • 需要多一个状态位,来到i时,手中是否有股票
  3. 代码

    class Solution:
    # 当前来到index位置,还可以买k次,state为0,则手里没有股票
    def process(self, prices: List[int], k: int, index: int, state: int, dp) -> int:
    if index == len(prices):
    return 0
    if dp[k][index][state] != -1:
    return dp[k][index][state]
    if state == 0: # 手里没有股票 index买或者不买
    if k == 0: # 不能买了
    return 0
    # 不买
    no = self.process(prices, k, index + 1, 0, dp)
    # 买
    yes = self.process(prices, k - 1, index + 1, 1, dp) - prices[index]
    else: # 手里有股票,决定卖或者不卖
    # 不卖
    no = self.process(prices, k, index + 1, 1, dp)
    # 卖
    yes = self.process(prices, k, index + 1, 0, dp) + prices[index]
    dp[k][index][state] = max(no, yes)
    return dp[k][index][state]
    def maxProfit(self, k: int, prices: List[int]) -> int:
    n = len(prices)
    dp = [[[-1] * 2 for _ in range(n)] for _ in range(k + 1)]
    return self.process(prices, k, 0, 0, dp)
posted @   ouyangxx  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示