leetcode 123: 买卖股票的最佳时机 III

本题跟122类似,但是更加绕了一点儿,122题可以看做多个分段求和的结果,而对于本题来说如果是递增或递减的数列,只需求整个数列最大值结果,而对于存在第i个数值大于第i-1并大于第i+1个值的数列,分成两个数列求两个数列的最大值,两个数列的最大值相加得到最大利润

int maxP(std::vector<int> &a,int s,int t){
    if(s==t)return 0;
    int max=0;
    int min=a[s];
    for(int i=s+1;i<=t;i++){
        if(a[i]-min>max)
            max=a[i]-min;
        if(a[i]<min)
            min=a[i];
    }
    return max;
}

int maxProfit(std::vector<int>&prices){
    int len=prices.size();
    if(len==0)return 0;
    std::vector<int>a;
    for(int i=1;i<len-1;i++){
        if(prices[i]>prices[i-1]&&prices[i]>=prices[i+1])
            a.push_back(i);
    }    
    int l=a.size();
    if(l==0) return maxP(prices,0,len-1);
    int max=0;
    int max1=0;
    int max2=0;
    for(int j=0;j<l;j++){
        max1=maxP(prices,0,a[j]);
        max2=maxP(prices,a[j]+1,len-1);
        if(max1+max2>max)
            max=max1+max2;
    }
    return max;
}

猜你喜欢

转载自blog.csdn.net/u013263891/article/details/82963302