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

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

在这里插入图片描述

看完题后的思路

  1. dp[i][]
    0: 第i天不持有股票的最大利润
    1: 持有

  2. 递推公式
    dp[i][0]=max(第i-1天不持有,第i-1天持有,在第i天卖了)
    dp[i][1]=max(第i-1天持有, 第i-2天不持有,第i天持有)

  3. 初始化
    dp[0][0]=0;
    dp[0][1]=-price[i];
    dp[1][0]=max(x,x)
    dp[1][1]=max(-price[0],=price[1])

代码

    public int maxProfit04(int[] prices) {
        if (prices.length==1){
            return 0;
        }
        int[][] dp=new int[prices.length][2];
        dp[0][0]=0;
        dp[0][1]=-prices[0];
        dp[1][0]=Math.max(dp[0][0],dp[0][1]+prices[1]);
        dp[1][1]=Math.max(dp[0][1],-prices[1]);


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

        return Math.max(dp[dp.length-1][0],dp[dp.length-1][1]); 
    }

看题接的收货

每天其实有四个状态
(1)今天持有股票 dp[i][3]=max(dp[i-1][3],dp[i][1]-price[i],dp[i][2]-price[i])
今天不持有股票
(2)今天卖出股票 dp[i][0] =dp[i-1][3]+price[i]
(3)今天是冷冻期(前天卖出股票) dp[i][1]=dp[i-1][0]
(3)今天不是冷冻期(两天前卖出股票) dp[i][2]=max(dp[i-1][2],dp[i-1][1])
在这里插入图片描述

初始化
dp[0][0]=0; // -1天买入,今天卖出
dp[0][1]=0; // 今天是冷冻期,-1天卖出,钱为0
dp[0][2]=0; // -1天为0,今天也是0
dp[0][3]=-price[0];

714.买卖股票的最佳时机含手续费

在这里插入图片描述

看完题目的思路

设卖出的时候付手续费

  1. dp[i][]
    0: 第i天不持有股票的最大利润
    1: 持有

  2. 递推公式
    dp[i][0]=max(dp[i-1][0],dp[i-1][1]+price[i]-fee)
    dp[i][1]=max(dp[i-1][1],dp[i-1][0]=price[i])

  3. 初始化
    dp[0][0]=0;
    dp[0][1]=-price[i];

代码

    public int maxProfit(int[] prices, int fee) {
        int[][] dp=new int[prices.length][2];
        dp[0][0]=0;
        dp[0][1]=-prices[0];

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

        return Math.max(dp[dp.length-1][0],dp[dp.length-1][1]);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

弈师亦友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值