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

可以买两次。

如果只是两次,确实很好做。两个数组记录该点前最大利润和该点后的最大利润,然后找出利润和最大的点便可。log n。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        vector<int> before(n,0);
        vector<int> after(n,0);
        
        for(int i = 1 ; i < n ;i++)
        {
            if(prices[i]-prices[i-1]+before[i-1]>0)
            before[i]= prices[i]-prices[i-1]+before[i-1];
            else
            before[i] = 0;
        }
        for(int i = n-2 ; i >= 0 ;i--)
        {
            if(prices[i+1] -prices[i] + after[i+1] > 0 )
            after[i] = prices[i+1] -prices[i] + after[i+1];
            else
            after[i] = 0;
        }
        int max =0;
        for(int i = 1; i < n ; i++)
        {
            if(before[i]<before[i-1])before[i]=before[i-1];
        }
        for(int i= n-2;i>=0;i--)
        {
            if(after[i]<after[i+1])after[i]=after[i+1];
        }
        for(int i = 0 ; i < n ; i++)
        {
            if(before[i] + after[i] > max)
            max = before[i] + after[i];
        }
        return max;
        
        
    }
};

  

posted on 2014-04-11 20:10  pengyu2003  阅读(168)  评论(0编辑  收藏  举报

导航