码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Best Time to Buy and Sell Stock III

时间:2014-07-22 22:34:54      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   

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

标签:style   blog   http   color   io   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!