Sunday, May 17, 2015

[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).
Analysis:

Just needs to calculate a vector, whose value at index i means the maximum profit from buying and selling once until the index. Also, it can hold the maximum profit from buying and selling from i+1 to end. Loop the array twice will get the vector.

You might be asked why can't you loop from the beginning firstly and from the end secondly in the following code.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(1 >= len) return 0;
        vector<int> profit(len, 0);
        int sell = prices[len-1];
        for(int i=len-2;i>=0;i--)
        {
            int diff = sell - prices[i];
            profit[i] = max(profit[i+1],  diff);
            if(diff<0) sell = prices[i];
        }
        
        int buy = prices[0];
        for(int i=1;i<len;i++)
        {
            int diff = prices[i] - buy;
            profit[i] = max(profit[i-1], profit[i] + diff);
            if(diff < 0) buy = prices[i];
        }
        
        return profit[len-1];
    }
};