leetcode309. 最佳买卖股票时机含冷冻期(dp)

class Solution {
    public int maxProfit(int[] prices) {
        // 1 2 3 0 2
        /* 
        have[i]表示第i天持有股票的最大值
        no[i]表示第i天没有持有股票的最大值

        // 如果是不包含冷冻期
        have[i] = max(have[i-1],no[i-1]-price[i]) (*)
        no[i] = max(no[i-1],have[i-1]+price[i])   (**)
        // 如果包含冷冻期
        (*)需要修改,no[i-1] = 第i-1天持有,但是i-1天卖出了,此时冷冻,第二天不能交易
                    no[i-1] = 第i-1天不持有,那么no[i-1] = no[i-2]
        have[i] = max(have[i-1],no[i-2]-price[i]) (*)
        */

        int len = prices.length;
        int[] have = new int[len];
        int[] no = new int[len];
        have[0] = -prices[0];
        for(int i=1;i<len;i++){
            if(i>=2){
                have[i] = Math.max(have[i-1],no[i-2]-prices[i]);
            }else{
                have[i] = Math.max(-prices[0],-prices[1]);
            }

            no[i] = Math.max(no[i-1],have[i-1]+prices[i]);
        }
        return Math.max(have[len-1],no[len-1]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值