Simple Javascript solution


  • 0
    H

    Keep track of the lowest number as you iterate through the array and keep track of highest profit which would be current number - lowest number kept track of and finding the max of it.
    This solution has time space complexity of O(N) time and O(1) space.

    var maxProfit = function(prices) {
      var ans = 0;
      var curLowest = prices[0];
      for (var i = 1; i < prices.length; i++){
          curLowest = Math.min(curLowest, prices[i]);
          ans = Math.max(prices[i] - curLowest, ans);
      }
      return ans;
    

    };


Log in to reply
 

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