leetcode - Best Time to Buy and Sell Stock III

leetcode - Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0) return 0;
        vector<int> pricesForward(prices.size(),0), pricesBackward(prices.size(),0);
        int low = prices[0], maxPrice = 0;
        for(int i = 1; i < prices.size(); i++){
            if(low > prices[i]){
                low = prices[i];
            }
            else if(maxPrice < prices[i] - low){
                maxPrice = prices[i] - low;
            }
            pricesForward[i] = maxPrice;
        }
        int high = prices[prices.size()-1]; 
        maxPrice = 0;
        for(int i = prices.size()-2; i >= 0; i--){
            if(high < prices[i]){
                high = prices[i];
            }
            else if(maxPrice < high - prices[i]){
                maxPrice = high - prices[i];
            }
            pricesBackward[i] = maxPrice;
        }
        int ans = 0;
        for(int i = 0; i < prices.size(); i++){
            if(pricesForward[i]+pricesBackward[i] > ans) ans = pricesForward[i]+pricesBackward[i];
        }
        return ans;
    }
};

自己开始的想法是错的,以为可以仿照前面的题求出最大的两个利润。结果发现显然是错的,因为这两个最大值可能是在重叠的序列上产生的。

 

看了网上的解答,都是考虑将序列分成两段,分别计算这两段的最大利润,然后找到最大的组合。但是如果对每一个分界点的前后两个序列每次都计算最大利润的话会TLE,

所以可以使用动态规划来做,分前向遍历和后向遍历。对于前向遍历,方法和之前的一样,要保存从0-i所能获得的最大利润,

后续遍历类似于前向遍历,但是不同之处在于,是找最大值(前向的时候是找最小值),并计算最大值与所遍历的元素的差。

 

例如:序列: 2 1 2 0 1

  前向遍历: 0 0 1 1 1

  后向遍历: 1 1 1 1 0

        组合: 1 1 2 2 1

最大值为2.

 

参考:

http://blog.csdn.net/jellyyin/article/details/8671277

http://www.cnblogs.com/lihaozy/archive/2012/12/19/2825525.html

http://www.tuicool.com/articles/NnAnYz

http://www.tuicool.com/articles/rMJZj2

转载于:https://www.cnblogs.com/shnj/p/4742799.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值