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

分析: First consider the case that when we are only allowed to make one transaction. we can handle this easily with DP. If we move forward, any new price we meet will only affect our history result by two ways:



will it be so low that it beats our previous lowest price?

will it be so high that we should instead sell on this time to gain a higher profit (than the history record)? Similarly, we can move backward with the highest price and profit in record. Either way would take O(n) time.

Now consider the two transaction case. Since there will be no overlaps, we are actually dividing the whole time into two intervals.



We want to maximize the profit in each of them so the same method above will apply here. We are actually trying to break the day at each time instance, by adding the potential max profit before and after it together. By recording history and future for each time point, we can again do this within O(n) time.



摘自 : http://discuss.leetcode.com/questions/287/best-time-to-buy-and-sell-stock-iii?sort=votes&page=1

  

class Solution {

public:

//III

    int maxProfit(vector<int> &prices) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        int len = prices.size();

        if(len < 2) return 0;

        

        int minheight, maxheight;

        vector<int> history(len, 0);

        vector<int> future(len, 0);

        

        minheight = prices[0];

        history[0] = 0;

        for( int i = 1; i< len; ++i){

            if(minheight > prices[i])

                minheight = prices[i];

    

            history[i] = history[i-1] > prices[i]- minheight ? history[i-1]

                                                             : prices[i] - minheight;        

        }

        

        

        int res = 0;

        maxheight = prices[len-1];

        future[len-1] = 0;

        for( int i = len -2; i>=0 ; --i){

            if(maxheight < prices[i])

                maxheight = prices[i];

                

            future[i] = future[i+1] > maxheight - prices[i] ? future[i+1]

                                                            : maxheight  - prices[i] ;

        

            res = res > future[i] + history[i] ? res : future[i]+ history[i]; 

        }

        

        return res;

    }

};

 

你可能感兴趣的:(LeetCode)