CoderJesse  
wangjiexi@CS.PKU

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

由于最多只能操作两次,最好的办法是,先用一个数组a[]记录第i天前能获得的最大利润,再用一个数组b[]记录后第i天及以后能获得的最大利润。

然后再循环一次,求出最大的 a[i] + b[i+1]即可。注意需要和只进行一次操作的情况比较一下,即将最大的 a[i] + b[i+1]和a[0]比较,求出更大的。

 

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() == 0 || prices.size() == 1)
            return 0;
        int *a = new int[prices.size()];
        int *b = new int[prices.size()];
        a[0] = 0;b[0] = 0;
        int max ;
        int max_price = prices.at(prices.size() - 1);
        int min_price = prices.at(0);
        max = 0;
        for(int i = 1; i < prices.size();i++)
        {
            if(max < prices.at(i) - min_price)
            {
                max = prices.at(i) - min_price;
            }
            else if(min_price > prices.at(i))
            {
                min_price = prices.at(i);
            }
            a[i] = max;
        }
        max = 0;
        for(int i = prices.size() - 2; i >= 0;i--)
        {
            if(max < max_price - prices.at(i))
            {
                max = max_price - prices.at(i);
            }
            else if(max_price < prices.at(i))
            {
                max_price = prices.at(i);
            }
            b[i] = max;
        }   
        max = 0;
        for(int i = 0;i < prices.size()-1;i++)
        {
            if(max < a[i] + b[i+1])
                max = a[i] + b[i+1];
        }
        if(max < b[0])
            max = b[0];
        return max;
    }
};

 

posted on 2013-02-28 12:19  CoderJesse  阅读(111)  评论(0)    收藏  举报