Focus on local min & max. each vibration is profit


  • 0
    int maxProfit(vector<int>& prices) {
        int n=prices.size();
        if(n<2) return 0;
        int pf=0, p, i, lp=prices[0];
        bool incOrDec=true;
        for(i=1; i<n; i++){
            p=prices[i]-prices[i-1];
            if(p<0 && incOrDec){incOrDec=false; pf+=prices[i-1]-lp;}
            else if(p>0 && !incOrDec){incOrDec=true; lp=prices[i-1];}
        }
        if(incOrDec) pf+=prices[n-1]-lp;
        return pf;
        
    }

Log in to reply
 

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