Saturday, August 17, 2013

Best Time to Buy and Sell Stock III

/*
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).
*/
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = prices.size();
        if(size <= 1) return 0;
       
        vector<int> localMaxForward;
        int maxProfitForward = 0;
        int minValueForward = prices[0];
        localMaxForward.push_back(maxProfitForward);
       
        int i;
        int temp;
        for(i=1; i<size; i++){
            if(prices[i] < minValueForward){
                minValueForward = prices[i];
            }
            else{
                temp = prices[i] - minValueForward;
               
                if(temp>maxProfitForward){
                    maxProfitForward = temp;
                }
            }
            localMaxForward.push_back(maxProfitForward);
        }
       
       
        vector<int> result;
        int maxProfitBackward = localMaxForward[size-1];
        int maxValueBackward = prices[size-1];
        result.insert(result.begin(), maxProfitBackward);
        for(i=size-2; i>=0; i--){
            if(prices[i] > maxValueBackward){
                maxValueBackward = prices[i];
            }
            else{
                temp = maxValueBackward - prices[i] + localMaxForward[i];
                if(temp>maxProfitBackward){
                    maxProfitBackward = temp;
                }
            }
            result.insert(result.begin(), maxProfitBackward);
        }
       
        return result[0];
    }
};

No comments:

Post a Comment