Algorithms · Sliding window

Best Time to Buy and Sell Stock

Buy one day, sell a later day: the most profit.

The problem

You get the price of a stock for each day. Buy on one day and sell on a later day. Return the most profit you could make, or 0 if no trade makes money.

max_profit([7, 1, 5, 3, 6, 4])5
max_profit([7, 6, 4, 3, 1])0
Sliding window. Update, don’t recount. A train window: one tree leaves on the left as another arrives on the right.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def max_profit(prices):take the price for each day
best = 0no profit yet
for buy in range(len(prices)):pick a day to buy
for sell in range(buy + 1, len(prices)):and a later day to sell
best = max(best, prices[sell] - prices[buy])keep the best profit
return bestthe most you could make

Now ask: what if there were a billion?

Trading systems watch millions of prices a second. They can’t look back over all of history on every tick, so they keep running numbers (like “cheapest so far”) and update them as each price arrives.

Aim for O(n)🧩 classic

Think it through

You sell today. Which day should you have bought?

  • Yesterday
  • The cheapest day before today
Show the answer

The cheapest day before today. Today’s best profit only depends on the lowest price so far. So you don’t need every pair of days.

What do you carry along as you read the prices?

  • Every price so far
  • The cheapest so far and the best profit so far
Show the answer

The cheapest so far and the best profit so far. Two numbers, one pass. The champion-so-far idea from Find the biggest, used twice.

Stuck? 3 nudges, smallest first
  1. If you sell today, which day should you have bought on?
  2. The cheapest day before today. So keep track of the cheapest price you’ve seen so far.
  3. One loop: cheapest = min(cheapest, p), then best = max(best, p - cheapest).

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def max_profit(prices):take the price for each day
cheapest = float("inf")the cheapest price so far (none yet)
best = 0no profit yet
for p in prices:walk through the days once
cheapest = min(cheapest, p)was today the cheapest day so far?
best = max(best, p - cheapest)selling today: is that a record profit?
return bestthe most you could make

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with sliding window