Best Time to Buy and Sell Stock III

来源:互联网 发布:fikker破解版linux 编辑:程序博客网 时间:2024/06/06 10:39
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).

思路:在整个过程中至多进行两次交易,求得最大的获取收益的价值。可以这样考虑,整个数组以prices[i]为分界线,前[0...i]中获得一个最大的profit.后面[i...prices.size()-1]的控件内再获得一个最大的profit。两者之和就是整个数组的最大的收益。每一部分求得最大收益的方式和这个类型I的解决方式一致。

具体代码如下所示:

class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.size()<2)//此时的条件不成立            return 0;        int low=prices[0];        int res=0;        vector<int>leftProfit(prices.size(),0);        for(int i=1;i<prices.size();i++)        {            if(prices[i]<low)                low=prices[i];            res=res>prices[i]-low?res:prices[i]-low;            leftProfit[i]=res;        }        //从后向前来计算        int high=prices[prices.size()-1];        int rightres=0;        res=0;        for(int i=prices.size()-2;i>=0;i--)        {            if(prices[i]>high)                high=prices[i];            rightres=rightres>high-prices[i]?rightres:high-prices[i];            res=res>rightres+leftProfit[i]?res:rightres+leftProfit[i];        }        return res;    }};


0 0
原创粉丝点击