Skip to content
16-Week DSA Roadmap
LeetCode #121EasyProblem 5 of 8

Best Time to Buy and Sell Stock

Given a stock's price for each day, find the biggest profit from buying once and selling once later.

  • Track the best so far in one pass
  • Running minimum

Before this, know: Arrays and loops, Min and max of two numbers

The problem in plain English

You get a list prices, where prices[i] is the price of one share of a stock on day i. You may buy once and then sell once on a later day. What is the biggest profit you can make? Profit = sell price − buy price.

If no trade makes money, the answer is 0 (you just don’t trade).

Example: prices = [7, 1, 5, 3, 6, 4].

prices (one dot per day)
+57day 01day 15day 23day 36day 44day 5
Buy on day 1 at price 1, sell on day 4 at price 6: profit 6 − 1 = 5. No other pair does better.

The rules that matter:

  • You must buy before you sell. Buying at 1 on day 1 and “selling” at 7 on day 0 would be time travel.
  • Only one buy and one sell.
  • If prices only fall, return 0.

Before you code: think it through

So for each day we need two things: today’s price, and the cheapest price on any day before today. Today’s best possible profit is their difference.

Pause and think

prices = [2, 4, 1]. On day 2 the price drops to 1, a new low. Does that change the answer?

Approach 1: Brute force

Try every buy day, and for each one every later sell day. Keep the biggest difference.

Brute force: every buy and sell pair

prices = [2, 4, 1]

prices (one dot per day)
2day 04day 11day 2
prices
  1. 20
  2. 41
  3. 12
variables
buy price
—
profit today
—
best
0
  • Buy day
  • Sell day
  • Best trade

Try every buy day, and for each one every later sell day. Keep the biggest profit.

Step 1 / 5

Which line is running?

function maxProfit(prices) {  let best = 0;Running now:   for (let buy = 0; buy < prices.length; buy++) {    for (let sell = buy + 1; sell < prices.length; sell++) {      best = Math.max(best, prices[sell] - prices[buy]);    }  }  return best;}

Brute force

function maxProfit(prices) {  let best = 0;  for (let buy = 0; buy < prices.length; buy++) {    for (let sell = buy + 1; sell < prices.length; sell++) {      best = Math.max(best, prices[sell] - prices[buy]);    }  }  return best;}
def max_profit(prices):    best = 0    for buy in range(len(prices)):        for sell in range(buy + 1, len(prices)):            best = max(best, prices[sell] - prices[buy])    return best

Why is it slow?

With 6 days there are 5 + 4 + 3 + 2 + 1 = 15 pairs. LeetCode allows 100,000 days: about 5 billion pairs. The work grows like n × n, O(n²). And most of that work is wasted: for each sell day, only one buy day matters, the cheapest one before it.

The pattern: track the best so far in one pass

You can also see this as two pointers: a buy pointer that stays on the cheapest day so far, and a sell pointer that walks forward one day at a time. The buy pointer only ever jumps forward, to a new low.

Pattern

Track the best so far in one pass

Template

Use it when: the answer for each position depends only on a summary of what came before it (the minimum, maximum or sum so far).

Signal words

  • “buy then sell later”
  • “maximum difference”
  • “later element minus earlier element”
  • “single pass”
  • “max profit”

Approach 2: One pass with the cheapest price so far

  1. Set minPrice to infinity (bigger than any price, so the first day always beats it) and best to 0.
  2. Go through the prices one day at a time.
  3. If today’s price is lower than minPrice, this is the new cheapest day to buy. Remember it.
  4. Otherwise, work out today’s profit, price − minPrice, and keep it if it beats best.
  5. After the last day, return best.

On the chart, the blue dot is the cheapest day so far (“buy”), the amber dot is today (“sell?”), and the green line is the best trade so far. Faded dots are future days the algorithm hasn’t seen yet: it never looks ahead.

One pass: cheapest price so far

prices = [7, 1, 5, 3, 6, 4]

prices (one dot per day)
7day 01day 15day 23day 36day 44day 5
prices
  1. 70
  2. 11
  3. 52
  4. 33
  5. 64
  6. 45
variables
minPrice
∞
profit today
—
best
0
  • Cheapest day so far (buy)
  • New cheapest day
  • Today (sell?)
  • Future: not seen yet
  • Best trade

Walk through the days once. We remember two things: the cheapest price so far (where we'd buy) and the best profit so far. Before day 0, the cheapest price is "infinity" and the best profit is 0.

Step 1 / 14

Which line is running?

function maxProfit(prices) {Running now:   let minPrice = Infinity; // cheapest price seen so far  let best = 0; // best profit seen so far  for (const price of prices) {    if (price < minPrice) {      minPrice = price; // a new cheapest day to buy    } else {      best = Math.max(best, price - minPrice); // what if we sell today?    }  }  return best;}

Try low comes last [2, 4, 1]: the buy pointer jumps to day 2, but the best trade stays at +2. And always falling: every day is a new low, so we never sell and the answer is 0.

The code, line by line

One pass with the cheapest price so far

function maxProfit(prices) {  let minPrice = Infinity; // cheapest price seen so far  let best = 0; // best profit seen so far  for (const price of prices) {    if (price < minPrice) {      minPrice = price; // a new cheapest day to buy    } else {      best = Math.max(best, price - minPrice); // what if we sell today?    }  }  return best;}
def max_profit(prices):    min_price = float("inf")  # cheapest price seen so far    best = 0  # best profit seen so far    for price in prices:        if price < min_price:            min_price = price  # a new cheapest day to buy        else:            best = max(best, price - min_price)  # what if we sell today?    return best

On LeetCode it’s var maxProfit = function(prices) in JavaScript, and def maxProfit(self, prices) inside class Solution in Python. Line numbers are the same in both languages until the end.

  • Line 2: minPrice starts at infinity (Infinity in JavaScript, float("inf") in Python), a value bigger than every real price, so the first day’s price always replaces it.
  • Line 3: best starts at 0, which is also the answer if we never trade.
  • Line 4: look at each day’s price in order. for … of (JS) and for … in (Python) hand us the values one by one.
  • Lines 5–6: a new low. Selling today would earn nothing (or lose money), so just remember it as the best day to buy from now on.
  • Lines 7–8: not a new low, so selling today makes price − minPrice (zero or more). If it beats best, keep it.
  • Line 11 (JS) / line 9 (Python): the best profit after looking at every day.

Dry run

prices = [7, 1, 5, 3, 6, 4]:

daypriceprice < minPrice?minPrice afterprofit if sold todaybest after
07yes (< ∞)7—0
11yes1—0
25no15 − 1 = 44
33no13 − 1 = 24
46no16 − 1 = 55
54no14 − 1 = 35
prices = [7, 1, 5, 3, 6, 4]

The day 4 row is where the answer appears. Notice minPrice settles at 1 on day 1 and every later day measures itself against it.

Complexity

Brute force

Time

O(n²)

Every buy day paired with every later sell day: about n × n ÷ 2 pairs.

Space

O(1)

Just the loop counters and best.

One pass

Time

O(n)

We look at each day exactly once. 100,000 days ≈ 100,000 steps.

Space

O(1)

Only two numbers, minPrice and best, however many days there are.

Common mistakes and edge cases

What to say out loud:

  1. “Brute force tries every buy-sell pair: O(n²).”
  2. “For any sell day, the best buy day is just the cheapest day before it.”
  3. “So one pass, keeping the minimum so far and the best profit so far: O(n) time, O(1) space.”
  4. Mention the falling-prices case and why the answer is 0.

Likely follow-up questions:

  • “What if you can buy and sell many times?” That’s Best Time to Buy and Sell Stock II: add up every price rise from one day to the next.
  • “What if you also need the days?” Store the index of the minimum and the best pair alongside the values (the visualizer does exactly that).
  • “Is this a sliding window?” You can see it that way: the window runs from the cheapest day to today, and its left edge jumps forward when a new low appears.

Related problems: