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

Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II

时间:2017-06-17 16:59:39      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:fit   class   value   ret   tor   nbsp   max   blog   return   

方法:记录便利过程中的best profit

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() < 2)
            return 0;
        
        int profit = 0, minValue = prices[0];
        
        for(int i=0; i<prices.size(); ++i)
        {
            profit = max(profit, prices[i] - minValue);
            
            if(prices[i] < minValue)
                minValue = prices[i];
        }
        
        return profit;
    }
};

Best Time to Buy and Sell Stock II

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sum = 0;
        
        for(int i=1; i<prices.size(); ++i)
        {
            if(prices[i] - prices[i-1] > 0)
                sum += prices[i] - prices[i-1];
        }
        
        return sum;
    }
};

 

Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II

标签:fit   class   value   ret   tor   nbsp   max   blog   return   

原文地址:http://www.cnblogs.com/chengyuz/p/7040437.html

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