123. 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.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len=prices.size();
        if(len<=0)
            return 0;
        vector<int> left(len);
        vector<int> right(len);
        int min=prices[0];
        for(int i=1;i<len;i++)
        {
            min=prices[i]<min?prices[i]:min;
            left[i]=prices[i]-min>left[i-1]?prices[i]-min:left[i-1];
        }
        int max=prices[len-1];
        for(int i=len-2;i>=0;i--)
        {
            max=prices[i]>max?prices[i]:max;
            right[i]=max-prices[i]>right[i]?max-prices[i]:right[i+1];
        }
        int res=0;
        for(int i=0;i<len;i++)
            res=res>(left[i]+right[i])?res:(left[i]+right[i]);
        return res;
    }
};
原文地址:https://www.cnblogs.com/qiaozhoulin/p/5818813.html