309. 买卖股票的最佳时机含冷冻期(leetcode)

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/

class Solution {
    public int maxProfit(int[] prices) {
        // f[i][2] 这里把不持有股票这个大状态划分成
        // 刚卖出股票(则下一天就是冷冻期),保持卖出状态,这两个子集,因为有冷淡期,不划分就区别不了冷冻了
        // f[i][0] 持股
        // f[i][1] 保持卖出
        // f[i][2] 卖出股票
        // f[i][3] 冷冻期
        // f[i][0] = max(f[i-1][0],f[i-1][1]-prices[i],f[i-1][3]-prices[i])
        // f[i][1] = max(f[i-1][1],f[i-1][3])
        // f[i][2] = f[i-1][0]+prices[i]
        // f[i][3] = f[i-1][2]
        // 初始化
        // f[1][0]=-prices[0];
        // f[i][1]=f[i][2]=f[i][3]=0;
        int n = prices.length;
        if (n == 0) return 0;
        int[][] f=new int[prices.length+1][4];
        f[1][0]=-prices[0];
        for(int i=2;i<=prices.length;i++)
        {
            f[i][0]=Math.max(f[i-1][0],Math.max(f[i-1][1]-prices[i-1],f[i-1][3]-prices[i-1]));
            f[i][1]=Math.max(f[i-1][1],f[i-1][3]);
            f[i][2]=f[i-1][0]+prices[i-1];
            f[i][3] = f[i-1][2];
        }
        return Math.max(f[prices.length][1],Math.max(f[prices.length][2],f[prices.length][3]));
    }
}

 

posted @ 2024-09-07 03:59  风乐  阅读(19)  评论(0)    收藏  举报