algorithm

Best Time to Buy and Sell Stock Algorithm

You get one shot. Buy once, sell once. Find the maximum profit.

27 Mar 2024

You get one shot. Buy once, sell once. Find the maximum profit.

The Problem

Given an array prices where prices[i] is the stock price on day i, find the best single transaction. You must buy before you sell. If no profit is possible, return 0.

Input: prices = [7,1,5,3,6,4]
Output: 5
Buy at 1 (day 2), sell at 6 (day 5). Profit = 5.

The Brute Force Trap

The naive approach checks every pair: for each buy day, look at every future sell day. That's O(n²). It works, but it's slow.

The Insight

You don't need to check every pair. As you scan left to right, track two things:

  1. The lowest price seen so far (your best buy opportunity).
  2. The maximum profit if you sold today.

One pass. Done.

The Code

Javascript
function maxProfit(prices) {
  let minPrice = Infinity;
  let maxProfit = 0;

  for (let i = 0; i < prices.length; i++) {
    if (prices[i] < minPrice) {
      minPrice = prices[i];
    } else {
      maxProfit = Math.max(maxProfit, prices[i] - minPrice);
    }
  }

  return maxProfit;
}

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

Complexity

  • Time: O(n) — single pass.
  • Space: O(1) — two variables.

Why It Works

At each price, you're asking: "If I sold right now, what's the best I could have done?" The answer is always currentPrice - lowestPriceSoFar. By tracking the running minimum, you never miss the optimal buy point.

The Trade-off

This only handles one transaction. If you're allowed multiple buys and sells, you need a different approach (see the Stock II problem). If there's a transaction fee or cooldown, you need dynamic programming.