Leetcode 123. Best Time to Buy and Sell Stock III

15 篇文章 0 订阅
9 篇文章 0 订阅

题目分析

最多只能买卖两次,发生两次交易行为,求最大利润

#

III是这三题中最难的。允许两次买卖,但同一时间只允许持有一支股票。也就意味着这两次买卖在时间跨度上不能有重叠(当然第一次的卖出时间和第二次的买入时间可以是同一天)。既然不能有重叠可以将整个序列以任意坐标i为分割点,分割成两部分:
prices[0:n-1] => prices[0:i] + prices[i:n-1]
对于这个特定分割来说,最大收益为两段的最大收益之和。每一段的最大收益当然可以用I的解法来做。而III的解一定是对所有0<=i<=n-1的分割的最大收益中取一个最大值。为了增加计算效率,考虑采用dp来做bookkeeping。目标是对每个坐标i:
1. 计算A[0:i]的收益最大值:用minPrice记录i左边的最低价格,用maxLeftProfit记录左侧最大收益
2. 计算A[i:n-1]的收益最大值:用maxPrices记录i右边的最高价格,用maxRightProfit记录右侧最大收益。
3. 最后这两个收益之和便是以i为分割的最大收益。将序列从左向右扫一遍可以获取1,从右向左扫一遍可以获取2。相加后取最大值即为答案。
下面这个链接包括三种方法

主要是参看这篇博客

class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<2) return 0;
        int n= prices.length;
        int [] left_max_profit =new int[n];
        int [] right_max_profit = new int[n];
        left_max_profit[0] = 0;

        int min = prices[0];
        for(int i=1; i<n;++i){
            // prices[i]-min 表示在该处卖出去的股票价格,
            left_max_profit[i] = Math.max(left_max_profit[i-1], prices[i]-min);
            min = Math.min(min,prices[i]);
        }
        right_max_profit[n-1] = 0;
        int max = prices[n-1];
        for(int i= n-2;i>=0;--i){
            right_max_profit[i] = Math.max(max-prices[i],right_max_profit[i+1]);
            max = Math.max(max, prices[i]);
        }
        int result = left_max_profit[0] +right_max_profit[0];
        for(int i=1;i<n;i++){
            result = Math.max(result,left_max_profit[i]+right_max_profit[i]);
        }
  return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值