C++ 6ms solution


  • 0
     int maxProfit(vector<int>& prices) {
            //m[i]=max{m[i-1],m[i-1]+prices[i]-min}
            if(prices.size()==0)
            return 0;
            vector<int>m(prices.size());
            int j=0;
            //Skip prices[i]>prices[i+1]
            while(prices[j]>prices[j+1]){
                m[j]=0;
                j++;
                if(j==prices.size()-1) return 0;
            }
            int min=prices[j];
            int Max=prices[j];
            for(int i=j+1;i<prices.size();i++){
                if(prices[i]>Max){
                m[i]=max(m[i-1],prices[i]-min);
                Max=prices[i];
                }else m[i]=m[i-1];
                if(prices[i]<min){
                min=prices[i];
                Max=0;
                }
            }
            return m[prices.size()-1];
        }
    

Log in to reply
 

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