Fork me on github

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

思路

动态规划,公有三种状态,持有,不持有但不能买,不持有但可买

注意状态的转换

代码

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length < 2){
            return 0;
        }
        int[][] dp = new int[prices.length][3];
        dp[0][0] = -prices[0];
        for(int i = 1; i < prices.length; i++){
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2] - prices[i]);
            dp[i][1] = dp[i - 1][0] + prices[i];
            dp[i][2] = Math.max(dp[i - 1][1], dp[i - 1][2]);
        }
        int maxProfit = Math.max(dp[prices.length - 1][1], dp[prices.length - 1][2]);
        return maxProfit;
    }
}

posted @ 2020-07-11 00:03  zjy4fun  阅读(160)  评论(0编辑  收藏  举报