LeetCode 123. 买卖股票的最佳时机 III

题目

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


思路

两次动态规划,第一次动态规划从前到后,第二次从后到前,然后在前后两次动态规划的结果和中找到最大值即可。


代码实现(Java)

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0, len = prices.length;
        int[] before = new int[len];
        int[] after = new int[len];
        before[0] = -prices[0];
        int min = prices[0];
        for(int i = 1; i<len; i++) {
            before[i] = Math.max(before[i-1],prices[i]-min);
            min = Math.min(min,prices[i]);
        }
        int maxValue = prices[len-1];
        for(int i = len-2; i>=0; i--) {
            after[i] = Math.max(after[i+1],maxValue - prices[i]);
            maxValue = Math.max(maxValue,prices[i]);
        }
        for(int i = 1; i<=len-1; i++) {
            max = Math.max(before[i-1] + after[i] , max);
        }
        return Math.max(before[len-1],max);
    }
}

坚持分享,坚持原创,喜欢博主的靓仔靓女们可以看看博主的首页博客!
您的点赞与收藏是我分享博客的最大赞赏!
博主博客地址: https://blog.csdn.net/weixin_43967679

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

jiachengren

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

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

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

打赏作者

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

抵扣说明:

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

余额充值