C++ o(n) 8mm, very simple code


  • 0
    L

    class Solution {

    public:

    int maxProfit(vector<int>& prices) {
        if(prices.size()<=1) return 0;
        int lprice=prices[0];
        int profit=0;
        for(int i=0;i<prices.size();i++){
            if(prices[i]-lprice>profit){
                profit=prices[i]-lprice;
            }
            if(prices[i]<lprice){
                lprice=prices[i];
            }
        }
        return profit;
    }
    

    };


  • 0
    E
    This post is deleted!

  • 0
    S

    Here lprice should be "lowest price".
    If need simpler:

    int maxProfit(vector<int>& prices) {
        int lprice=INT_MAX;
        int profit=0;
        for(int i=0;i<prices.size();i++){
            profit = max(profit, prices[i] - lprice);
            lprice = min(lprice, prices[i]);
        }
        return profit;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.