8ms c++ solution with only 6 lines of code


  • 14
    J
    int maxProfit(vector<int>& prices) {
      if(prices.size() <= 1) return 0;
    
      int res = 0;
    
      for( size_t i = 1; i < prices.size(); i++)
        if( prices[i] - prices[i-1] > 0 ) 
          res += prices[i] - prices[i-1];
      
      return res;
    }

  • 1
    L

    mine is similar:

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

Log in to reply
 

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