best-time-to-buy-and-sell-stock leetcode C++

Say you have an array for which the i th element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

C++

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int maxPro = 0;
        int curMin = prices[0];
        for(int i =1; i < prices.size();i++){
            if (prices[i] < curMin) 
                curMin = prices[i];
            else
                maxPro = max(prices[i] - curMin,maxPro);
        }
        return maxPro;
    }
    
    int maxProfit4(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int maxPro = 0;
        int curMin = prices[0];
        for(int i =1; i < prices.size();i++){
            int cur = prices[i];
            if (cur < curMin) 
                curMin = cur;
            else{
                int curPro = cur - curMin;
                if (curPro > maxPro)
                    maxPro = curPro;
            }
        }
        return maxPro;
    }
    
    int maxProfit2(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int maxPro = 0;
        int curMin = prices[0];
        for(int i =1; i < prices.size();i++){
            if (prices[i] < curMin) 
                curMin = prices[i];
            else
                if (prices[i] - curMin > maxPro)
                    maxPro = prices[i] - curMin;
        }
        return maxPro;
    }
};
原文地址:https://www.cnblogs.com/vercont/p/10210292.html