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 @ 2025-01-09 14:07  ouyangxx  阅读(8)  评论(0)    收藏  举报