LeetCode.309.最佳买卖股票时机含冷冻期

原题链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/。
建立动态规划的递归方程:
第i的收益依赖第i-1的收益情况。每一天有三种情况,有买入、卖出、的冷冻三个状态,分情况建立递归方程。
第i天的三个状态为:buy,sell,cooldown
第i-1天的三个状态为:prebuy,presell,precooldown
递归方程如下:
buy = max(prebuy, precooldown - prices[i])
sell = max(presell, prebuy + prices[i])
cooldown = max(precooldown.prebuy,presell)

代码如下:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if n == 0:
            return 0
        sell = 0
        buy = -prices[0]  # 第一天的前一天是买入的最大利润是-prices[0]
        cool = 0
        
        for i in range(1,n):
            presell = sell
            prebuy = buy
            sell = max(buy + prices[i], sell)
            buy = max(cool - prices[i], buy)
            cool =  max(presell, prebuy, cool)
        return sell

你可能感兴趣的:(算法)