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 sub(vector<int>& prices,int s,int e,int& is,int& ie){
        if(e<=s){
            return 0;
        }
        //find max
        int max1=0,min1=prices[s];
        int tmps=s;
        is=-1,ie=-1;
        for(int i=s+1;i<=e;i++){
            if(prices[i]>=min1){
                if(max1<prices[i]-min1){
                    max1=prices[i]-min1;
                    is=tmps;
                    ie=i;
                }
            }
            else{
                min1=prices[i];
                tmps=i;
            }
        }
        if(ie==-1)return 0;
        return max1;
    }
    int sub2(vector<int>& prices,int s,int e,int& is,int& ie){
        if(e<=s){
            return 0;
        }
        //find max
        int max1=0,min1=prices[e];
        int tmpe=e;
        is=-1,ie=-1;
        for(int i=e-1;i>=s;i--){
            if(prices[i]>=min1){
                if(max1<prices[i]-min1){
                    max1=prices[i]-min1;
                    is=i;
                    ie=tmpe;
                }
            }
            else{
                min1=prices[i];
                tmpe=i;
            }
        }
        if(is==-1)return 0;
        return max1;
    }
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(prices.size()==0){
            return 0;
        }
        //find max
        int start,end;
        int m1=sub(prices,0,prices.size()-1,start,end);
        if(m1==0)return 0;
        int m2,m3,m4;
        int tmp1,tmp2;
        m2=sub(prices,0,start-1,tmp1,tmp2);
        m3=sub(prices,end+1,prices.size()-1,tmp1,tmp2);
        m4=sub2(prices,start,end,tmp1,tmp2);
        int ret=m1+m2;
        if(m1+m3>ret)ret=m1+m3;
        if(m1+m4>ret)ret=m1+m4;
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/superzrx/p/3355505.html