leetcode 309. 最佳买卖股票时机含冷冻期 中等 动态规划

题目:
在这里插入图片描述

分析:因为可以多次交易加上交易后有冷冻期的条件限制,所以用贪心算法的思想是做不出来的。每天的股票都有几种可能的状态,持有股票、不持有股票或保持原状(保持原状包括了处于冷冻期),我们如果研究出这几种状态的关系那么就有助于我们求解问题了。
1.持有股票状态。可能是前一天持有,今天保持;或者前一天处于冷冻期,今天买
2.不持有股票状态。可能是前一天不持有,今天保持;或者前一天买了,今天卖
3.冷冻期。只能是前一天卖了。
当前问题的解需要子问题的解,从最小的问题出发,自底向上的动态规划做法

代码:

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

在这里插入图片描述
在这里插入图片描述

发布了134 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_40208575/article/details/104703580