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

LeetCode Best Time to Buy and Sell Stock

时间:2014-05-22 05:09:49      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   java   

bubuko.com,布布扣
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int len = prices.size();
        if (len < 1) return 0;
        int minv = prices[0];
        int maxv = prices[0];
        int mprofit = 0;
        for (int i=1; i<len; i++) {
            int cur = prices[i];
            if (cur < minv) {
                minv = cur;
                maxv = cur;
            }
            if (cur > maxv) {
                maxv = cur;
                if (maxv - minv > mprofit) mprofit = maxv - minv;
            }
        }
        
        return mprofit;        
    }
};
bubuko.com,布布扣

这个解法应该算是贪婪吧,还可以把后缀序列的最大值求出来,然后在扫一边每个元素就可以知道如果当前买入,在后面的最高价是多少,从而求出最高利润,如果是负值则不进行交易,利润为0,下面给出dp版本的代码

bubuko.com,布布扣
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int len = prices.size();
        if (len < 2) return 0;
        vector<int> maxv(len, 0);
        maxv[len - 1] = prices.back();
        for (int i = len - 2; i>=0; i--) {
            if (prices[i] > maxv[i + 1]) {
                maxv[i] = prices[i];
            } else {
                maxv[i] = maxv[i + 1];
            }
        }
        int mprofit = 0;
        for (int i=0; i<len; i++) {
            int profit = maxv[i] - prices[i];
            if (profit > mprofit) mprofit = profit;
        }
        return mprofit;
    }
};
bubuko.com,布布扣

两者都是O(n)时间,只不过后者用了额外空间

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

LeetCode Best Time to Buy and Sell Stock

标签:style   blog   class   c   code   java   

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

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