#121 Best Time to Buy and Sell Stock

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() < 2)return 0;
    
        int minLop = 0,maxLop = 0;
        int maxProfit = 0;
        
        int idx = 1;
        while(idx < prices.size()){
            if(prices[idx] > prices[maxLop]){//find larger
                maxLop = idx;
                
                int profit = prices[maxLop] - prices[minLop];
                if(profit > maxProfit){
                    maxProfit = profit;
                }
            }
            else if(prices[idx] < prices[minLop]){//find smaller
                minLop = idx;
                maxLop = idx;
                
            }
            idx++;
        }
        
        return maxProfit;
    }
};

  

posted @ 2017-10-25 15:48  东方春  阅读(125)  评论(0)    收藏  举报