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

动态规划

class Solution {
    public int maxProfit(int[] prices) {

        if (prices.length == 1){
            return 0;
        }

        int[][] dp = new int[prices.length][4];

        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        dp[0][2] = 0;
        dp[0][3] = 0;

        /**
         * 总共有4种状态
         * dp[i][0]:持有股票(可能是之前买的,可能是前天卖了今天买的,可能是更早之前卖了今天买的)
         * dp[i][1]:今天卖出(肯定之前买的,今天卖了)
         * dp[i][2]:昨天卖出,今天冷冻期(肯定是昨天卖了)
         * dp[i][3]:前天之前卖出(可能是前天卖的,可能更早之前就卖了)
         */
        for (int i = 1; i < prices.length; i++) {

            dp[i][0] = Math.max(dp[i - 1][0], Math.max(dp[i - 1][2] - prices[i], dp[i - 1][3] - prices[i]));
            dp[i][1] = dp[i - 1][0] + prices[i];
            dp[i][2] = dp[i - 1][1];
            dp[i][3] = Math.max(dp[i - 1][2], dp[i - 1][3]);
        }

        /**
         * 最后三种状态都可以取得最大值(因为都卖出去了)
         */
        return Math.max(dp[prices.length - 1][1], Math.max(dp[prices.length - 1][2], dp[prices.length - 1][3]));
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

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

posted @ 2022-02-28 19:56  振袖秋枫问红叶  阅读(29)  评论(0)    收藏  举报