首页 > 其他 > 详细

LeetCode Best Time to Buy and Sell Stock III

时间:2014-07-22 22:34:45      阅读:306      评论:0      收藏:0      [点我收藏+]
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int len = prices.size();
        if (len < 2) return 0;

        vector<int> i2r(len, 0);
        vector<int> i2l(len, 0);

        int max_price = prices[len - 1];

        for (int i=len-2; i>=0; i--) {
            if (prices[i] > max_price) max_price = prices[i];
            int cp = max_price - prices[i];
            i2r[i] = cp > i2r[i + 1] ? cp : i2r[i + 1];
        }

        int min_price = prices[0];

        for (int i=1; i<len; i++) {
            if (prices[i] < min_price) min_price = prices[i];
            int cp = prices[i] - min_price;
            i2l[i] = cp > i2l[i - 1] ? cp : i2l[i - 1];
        }


        int mp = 0;

        for (int i=0; i<len; i++) {
            int p = i2l[i] + i2r[i + 1 >= len ? len - 1 : i + 1];
            if (p > mp) mp = p;
        }

        return mp;
    }
};

参考:http://www.cnblogs.com/zhuli19901106/p/3516813.html

LeetCode Best Time to Buy and Sell Stock III,布布扣,bubuko.com

LeetCode Best Time to Buy and Sell Stock III

原文:http://www.cnblogs.com/lailailai/p/3860797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!