Best Time to Buy and Sell Stock III

来源:互联网 发布:淘宝一千零一夜第二季 编辑:程序博客网 时间:2024/05/20 07:14

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) {        int n=prices.size();        if(n==0) return 0;        int a[111111],b[111111];        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        int tmp=prices[0];        a[0]=0;        for(int i=1;i<n;i++){            a[i]=max(a[i-1],prices[i]-tmp);            tmp=min(tmp,prices[i]);        }        tmp=prices[n-1];        b[n-1]=0;        for(int i=n-2;i>=0;i--){            b[i]=max(b[i+1],tmp-prices[i]);            tmp=max(tmp,prices[i]);        }        int ans=0;        for(int i=0;i<n;i++)          ans=max(ans,a[i]+b[i]);        return ans;    }};


0 0