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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 

Subscribe to see which companies asked this question

第一次用dp写n^2挂了。超时。后来 看的讨论里面的代码。太弱了
 
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n=prices.size();
        if(n<=1)return 0;
        int dp1[n]={0};
        int dp2[n]={0};
        int Min=prices[0];
        for(int i=1;i<n;i++){
            dp1[i]=max(dp1[i-1],prices[i]-Min);
            Min=min(Min,prices[i]);
        }
        int Max=prices[n-1];
        for(int i=n-2;i>=0;i--){
            dp2[i]=max(dp2[i+1],Max-prices[i]);
            Max=max(Max,prices[i]);
        }
        int ans=0;
        for(int i=0;i<n;i++){
            ans=max(ans,dp1[i]+dp2[i]);
        }
        return ans;
    }
};

 

posted on 2016-05-25 10:45  Beserious  阅读(126)  评论(0编辑  收藏  举报