代码随想录算法训练营 day 51: ● 309.最佳买卖股票时机含冷冻期 ● 714.买卖股票的最佳时机含手续费 ●总结

62 阅读1分钟

309. Best Time to Buy and Sell Stock with Cooldown

状态转移没想出来。

image.png

有了这个图就不难写。

class Solution {
    public int maxProfit(int[] prices) {
        //0 buy 1 selling 2 cooldown 3 sold

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

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

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

        return Math.max(dp[prices.length - 1][1], Math.max(dp[prices.length - 1][2], dp[prices.length - 1][3]));

    }
}

714. Best Time to Buy and Sell Stock with Transaction Fee 这题要容易点,但一开始把手续费当成了买和卖都要收。结果是一笔买卖只收一次。

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int[][] dp = new int[prices.length][3];

        //0 buy 1 sell

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

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

        return dp[prices.length - 1][1];
        
    }
}