【刷题1】LeetCode 309. 买卖股票时机含冷冻期 java题解

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

题目

在这里插入图片描述

分析

这里的「处于冷冻期」指的是在第 i 天结束之后的状态。也就是说:如果第 i 天结束之后处于冷冻期,那么第 i+1 天无法买入股票。
在这里插入图片描述

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

代码

class Solution {
    public int maxProfit(int[] prices) {
        int n=prices.length;
        int[][] f=new int[n][3];
        f[0][0]=-prices[0];//第0天持有股票,说明是第0天买的
        f[0][1]=0;//今天结束后处于冷冻
        f[0][2]=0;//今天结束后处于不冷冻
        for(int i=1;i<n;i++){
            //昨天持有 或 今天刚买(昨天结束后不在冷冻期)
            f[i][0]=Math.max(f[i-1][0],f[i-1][2]-prices[i]);
            //今天卖出变冷冻(昨天持有)
            f[i][1]=f[i-1][0]+prices[i];
            //今天结束后不冷冻且不持有,说明昨天也不持有,今天保持昨天的状态
            f[i][2]=Math.max(f[i-1][1],f[i-1][2]);
        }
        return Math.max(f[n-1][1],f[n-1][2]);
    }
}

空间优化过的代码

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0)
            return 0;
        int n=prices.length;
        //int[][] f=new int[n][3];
        int f0=-prices[0];
        int f1=0;
        int f2=0;
        int nf0,nf1,nf2;
        for(int i=1;i<n;i++){
            nf0=Math.max(f0,f2-prices[i]);
            nf1=f0+prices[i];
            nf2=Math.max(f1,f2);
            //赋值给下一轮要用的f0,f1,f2
            f0=nf0;
            f1=nf1;
            f2=nf2;
        }
        return Math.max(f1,f2);
    }
}

结果

在这里插入图片描述

复杂度

时间复杂度O(N)
空间复杂度O(1)

二、

class Solution {
    public int maxProfit(int[] prices) {
        int len=prices.length;
        if(len==0||len==1)
            return 0;
        int[] hold=new int[len];
        int[] unhold=new int[len];
        hold[0]=-prices[0];
        unhold[0]=0;
        hold[1]=Math.max(-prices[0],-prices[1]);
        unhold[1]=Math.max(unhold[0],hold[0]+prices[1]);
        for(int i=2;i<len;i++){
            hold[i]=Math.max(hold[i-1],unhold[i-2]-prices[i]);
            unhold[i]=Math.max(unhold[i-1],hold[i-1]+prices[i]);
        }
        return unhold[len-1];
    }
}
class Solution {
    public int maxProfit(int[] prices) {
        int rest=0;
        int sold=0;
        int hold=Integer.MIN_VALUE;
        int preSold,preHold;
        for(int price:prices){
            preSold=sold;
            preHold=hold;
            hold=Math.max(preHold,rest-price);
            sold=preHold+price;
            rest=Math.max(rest,preSold);
        }
        return Math.max(rest,sold);
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值