Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

How do you find the maximum profit from buying and selling a stock once?

SHORT ANSWER

Scan once while tracking the lowest price so far. At each day, the best profit if you sell today is price minus that lowest price. Keep the maximum of those.

Explain it simply

You can only buy once and sell once later. Imagine looking at a Sensex chart with hindsight. For each day you would ask: if I sell today, what was the cheapest day before it? The gap between today and that cheapest day is your profit.

So walk left to right, remember the cheapest price seen, and compare today's price against it.

Example

js
function maxProfit(prices) {
  let minPrice = Infinity;
  let best = 0;
  for (const price of prices) {
    if (price < minPrice) minPrice = price;
    else best = Math.max(best, price - minPrice);
  }
  return best;
}

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

Complexity

Time O(n), space O(1).

What to say in the interview

"I keep the minimum price seen so far and, for each day, compute the profit if I sold that day. The answer is the largest such profit, or 0 if prices only fall. One pass, O(n) time, O(1) space. Checking every buy and sell pair would be O(n squared)."

Common mistakes

  • Taking the global minimum and global maximum without checking that the minimum comes first.
  • Returning a negative number when no profit is possible.

#arrays#greedy

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.