代码随想录算法训练营第五十一天|动态规划part12|● 309.最佳买卖股票时机含冷冻期 ● 714.买卖股票的最佳时机含手续费 ●总结

●  309.最佳买卖股票时机含冷冻期   Best Time to Buy and Sell Stock with Cooldown - LeetCode

dp[i][0]: 持有股票的状态

dp[i][1]: 保持卖出股票的状态

dp[i][2]: 具体卖出股票的状态

dp[i][3] 冷冻期

dp[i][0] 延续前一天dp[i-1][0] 

                买入 dp[i -1][3] - prices[i]

                买入 dp[i - 1][1] - prices[i]

dp[i][1]  max(dp[i - 1][1] , dp[i - 1][3])

dp[i][2]         dp[i - 1][0] + prices[i]

dp[i][3]         dp[i - 1][2]

dp[0][0] = -price[0]

dp[0][1] = 0;

dp[0][2] = 0;

dp[0][3] = 0;

遍历顺序:从前往后

打印dp数组

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        int n = prices.length;
        int[][] dp = new int[n][4];

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

        return Math.max(dp[n - 1][3], Math.max(dp[n - 1][1], dp[n - 1][2]));
    }
}

●  714.买卖股票的最佳时机含手续费  Best Time to Buy and Sell Stock with Transaction Fee - LeetCode

dp[i][0]持有股票的最大现金 max(dp[i - 1][0], dp[i - 1][1] - prices[i])

dp[i][1]不持有股票的最大现金 Max(dp[i - 1][1], dp[i - 1][0] + prices[i] -fee)

class Solution {
    //dp[i][0]持有股票
    //dp[i][1]不持有股票
    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        dp[0][0] = -prices[0];
        dp[0][1] = 0;

        for (int i = 1; i < n; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
        }

        return dp[n - 1][1];
    }
}

● 总结

你可能感兴趣的:(代码随想录算法训练营,动态规划,算法)