Q8: Best Time to Buy and Sell Stock

Find the maximum profit possible from buying stock on one day and selling it on a future day given an array of daily stock prices.

Max Profit Calculator
function maxProfit(prices) {
  let minPrice = Infinity;
  let maxProfit = 0;
  
  for (let price of prices) {
    if (price < minPrice) {
      minPrice = price;
    } else if (price - minPrice > maxProfit) {
      maxProfit = price - minPrice;
    }
  }
  return maxProfit;
}

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

Tracks minPrice encountered up to the current day. Max profit is updated if selling today yields higher profit than previously recorded maximum.

Key Takeaways
  • Single pass algorithm maintaining lowest price seen so far.

  • Achieves O(n) time and O(1) auxiliary space complexity.

Knowledge Check

What profit is returned if stock prices strictly decrease continuously (e.g. [7, 6, 4, 3, 1])?