#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;
    }
};

  

原文地址:https://www.cnblogs.com/dongfangchun/p/7729262.html