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

方法:记录便利过程中的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;
    }
};

 

posted @ 2017-06-17 15:56  chengcy  Views(158)  Comments(0Edit  收藏  举报