Categories
interview

Best time to buy and sell stock

/**
 * @param {number[]} prices
 * @return {number}
 */
const maxProfit = function(prices) {
  let min = prices[0];
  let max = 0;
  for (const price of prices) {
    min = Math.min(min, price);
    max = Math.max(max, price - min);
  }
  return max;
};

console.log(maxProfit([7, 1, 5, 3, 6, 4])); // 5

Demo

n = size of input array

Time complexity: O(n)

Space complexity: O(1)