Clear JavaScript Solution


  • 0
    A

    Here is the editorial solution, but done with JavaScript and written (IMO) a bit more clearly.

    function maxProfit(prices) {
      var minPrice = prices[0];
      var maxProfit = 0;
      var length = prices.length;
      for (let i = 0; i < length; ++i) {
          var current = prices[i];
          var difference = current - minPrice;
          if (current < minPrice) minPrice = current;
          if (difference > maxProfit) maxProfit = difference;
      }
      return maxProfit;
    }
    

Log in to reply
 

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