309. 最佳买卖股票时机含冷冻期 714. 买卖股票的最佳时机含手续费

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

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

class Solution {
    public int maxProfit(int[] prices) {
        int length = prices.length;
        int[] dp = new int[4];
        dp[0] = -prices[0];
        for(int i = 0;i < length;i++){
            int temp1 = dp[0];
            int temp2 = dp[2];
            //买入状态:一直持有股票,前一天不持有当天买入(加上之前卖出的利润),前一天是冰冻期时当天买入
            dp[0] = Math.max(dp[0],Math.max(dp[1] - prices[i],dp[3] - prices[i]));
            //卖出状态中的一直不持有:前一天也不持有,前一天是冷冻期
            dp[1] = Math.max(dp[1],dp[3]);
            //卖出状态中的当天卖出(前面肯定没有冷冻期并且一定持有股票才会卖):之前买入现在卖出
            dp[2] = temp1 + prices[i];
            //冷冻期(前一天肯定卖了才会有冷冻期),前一天的当天卖出
            dp[3] = temp2;
        }
        return Math.max(dp[1],Math.max(dp[2],dp[3]));
    }
}

在这里插入图片描述

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

在这里插入图片描述
贪心算法:
不太好想,买入的时候加上手续费

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int buy = prices[0] + fee;
        int sum = 0;
        for(int price:prices){
            if(price > buy){
                sum += price - buy;
                buy = price;
            }else if(price + fee < buy){
                buy = price + fee;
            }
        }
        return sum;
    }
}

在这里插入图片描述
比较好理解就是卖出时候减去手续费即可

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int[] dp = new int[2];
        dp[0] = -prices[0];

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

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

龙崎流河

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

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

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

打赏作者

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

抵扣说明:

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

余额充值