Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Refer: http://blog.unieagle.net/2012/12/05/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Abest-time-to-buy-and-sell-stock-iii%EF%BC%8C%E4%B8%80%E7%BB%B4%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/

If you had a O(n) to "Best Time to Buy and Sell Stock", it is not that far away from an AC to III. Initially, it reminds me http://poj.org/problem?id=2479, and I think they are quite similar.

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        size_t len = prices.size();
        if (len <= 1) return 0;

        int maxProfit = 0;

        //    Pass 1: as Best Time to Buy and Sell Stock 
        vector<int> dp; dp.push_back(0);
        int lowest = prices[0];
        for (int i = 1; i < prices.size(); i++)
        {
            int currP = prices[i] - lowest;
            if (currP > maxProfit) maxProfit = currP;
            if (prices[i] < lowest) lowest = prices[i];

            dp.push_back(maxProfit);
        }

        //    Pass 2: 
        int ret = 0;
        maxProfit = 0;
        int highest = prices[len - 1];
        for (int i = len - 2; i >= 0; i--)
        {
            int currP = highest - prices[i];
            if (currP > maxProfit) maxProfit = currP;
            if (prices[i] > highest) highest = prices[i];

            //
            int currTotal = dp[i] + maxProfit;
            if (currTotal > ret) ret = currTotal;
        }
        return ret;
    }
};
posted on 2014-08-19 11:42  Tonix  阅读(177)  评论(0)    收藏  举报