THN Interview Prep

121. Best Time to Buy and Sell Stock

At a Glance

  • Topic: Array
  • Pattern: Sliding Window / Two Pointers
  • Difficulty: Easy
  • LeetCode: 121

Problem Statement

Find the maximum profit you can achieve from a single buy and sell transaction.

Approach & Solution Steps

Maintain a variable for the minimum price seen so far. Iterate through the array, updating the minimum price and calculating the maximum profit at each step.

Optimal JS Solution

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

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page