Best Time to Buy and Sell Stock solution explained
The Best Time to Buy and Sell Stock solution is a single pass that remembers the lowest price seen so far and, at each later day, asks how much selling today would earn against that low. The largest such gap is the answer, or 0 if prices never rise, which takes O(n) time and O(1) extra space.
By Evin JohnPublished 8 min read
What the problem asks
Picture a chart of one share's closing price, one number per day, in time order. You are allowed a single round trip: buy on one day, sell on some strictly later day. Work out the biggest profit that round trip can produce. If every possible sale would lose money or break even, the right move is to never trade, so the answer is 0. You return the amount, not the days, unless the interviewer asks for them.
| Prices by day | Best profit | Reason |
|---|---|---|
| [9, 4, 11, 2, 6] | 7 | Buy at 4, sell at 11. The later dip to 2 only reaches 6, a gain of 4 |
| [10, 8, 5, 5, 1] | 0 | Prices only fall or stay flat, so no trade pays |
| [1, 6, 0, 5] | 5 | Two different trades tie at 5; the amount is what counts |
| [3] | 0 | One day leaves nothing to sell into |
The first row is the one to keep in mind. The lowest price of the whole series is 2, yet buying there is not the best trade, because the peak came earlier. Any answer that grabs the global minimum and the global maximum separately will get rows like this wrong. Useful questions before you start: may the list be empty, are prices whole numbers, and should a losing market return 0 or the least bad loss?
Why it keeps showing up in screens
It is a fair test of one habit: noticing that a pair problem with an ordering rule can be solved by carrying a summary of the past instead of looking back over it. The time-order constraint (sell after you buy) is what makes the naive min and max idea fail, and spotting that is half the credit. It also opens a whole family of trading variants, so an interviewer can keep the same setup and raise the difficulty for as long as the round allows.
Variants an interviewer may add
- As many trades as you like, one share at a time. Add up every day-to-day rise. Each upward step is profit you could capture, and the sum equals the best sequence of trades.
- At most two trades. Track four running values: best balance after the first buy, after the first sale, after the second buy and after the second sale. Still one pass and constant space.
- At most k trades. Generalize the previous idea to k pairs of states, which gives O(n·k) time. When k is at least half the number of days, it reduces to the unlimited case.
- A fee on every sale, or a rest day after selling. Keep two or three states (holding, not holding, cooling down) and update them together each day.
- Report the buy and sell days. Remember the index of the cheapest price, and save the pair whenever the best gain improves. Code for this one is below.
Brute force: try every buy day against every later day
Fix a buy day, scan every later day as a possible sale, and keep the largest difference. With n days that is about n²/2 comparisons and no extra memory. It is easy to get right, which makes it a good first sentence, and it gives you a slow reference to test the fast version against.
def max_gain_slow(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 bestOptimal approach: carry the cheapest price forward
Look at what the inner loop needs for a given sell day. It only cares about the smallest price before that day; every other earlier price is irrelevant. So keep that smallest price in a variable as you walk forward. On each day, first ask what selling today would earn against the cheapest earlier price, and update the best gain. Then, if today is cheaper than anything before, make it the new cheapest. One loop, two variables.
Why is this safe? The optimal trade sells on some day s. At the moment the loop reaches s, the running minimum holds the lowest price among days before s, which is exactly the best buy for that sale. So the loop evaluates the optimal pair at some point and cannot miss it. That one-sentence argument is worth saying in the interview.
def max_gain(prices):
cheapest = float("inf")
best = 0
for price in prices:
if price < cheapest:
cheapest = price
elif price - cheapest > best:
best = price - cheapest
return bestfunction maxGain(prices) {
let cheapest = Infinity;
let best = 0;
for (const price of prices) {
if (price < cheapest) cheapest = price;
else if (price - cheapest > best) best = price - cheapest;
}
return best;
}The if and else-if order is fine here: when today sets a new low, selling today against an earlier price would be a loss anyway, so skipping the profit check on that day loses nothing. If you find that subtle, compute the profit first and update the minimum second. Both orders pass the tests.
def best_trade_days(prices):
low_day = 0
best, days = 0, None
for day in range(1, len(prices)):
gain = prices[day] - prices[low_day]
if gain > best:
best, days = gain, (low_day, day)
if prices[day] < prices[low_day]:
low_day = day
return best, daysdef max_gain_many_trades(prices):
total = 0
for day in range(1, len(prices)):
rise = prices[day] - prices[day - 1]
if rise > 0:
total += rise
return totalComplexity at a glance
| Version | Time | Extra space | Note |
|---|---|---|---|
| Every buy and sell pair | O(n²) | O(1) | Good opening line and test oracle |
| Running minimum, one trade | O(n) | O(1) | The expected answer |
| Running minimum with days | O(n) | O(1) | Same loop, one extra index |
| Unlimited trades | O(n) | O(1) | Sum of positive day-to-day changes |
| At most k trades | O(n·k) | O(k) | State machine with k buy and sell slots |
Edge cases worth a test
- No days or a single day: there is no sale, so the answer is 0.
- Prices that never rise, such as [10, 8, 5, 5, 1]: the answer is 0, not a negative number.
- A flat series like [4, 4, 4]: equal prices earn nothing, still 0.
- The overall low comes after the overall high, as in [9, 4, 11, 2, 6]. This is the case that breaks a global min and max shortcut.
- The best buy is the very first day or the best sale is the very last day. Make sure the loop includes both ends.
- Very large prices in a fixed-width integer type. A difference of two values cannot overflow if both fit and are non-negative, but say you checked.
Mistakes interviewers see often
- Subtracting the smallest price from the largest without respecting time order.
- Starting the best gain at the first difference instead of 0, which returns a negative number for a falling market.
- Starting the running minimum at 0 rather than at infinity or the first price, which makes every later price look profitable.
- Tracking the index of the lowest price and the index of the highest price separately when asked for the days. The two can come out with the sale before the purchase.
- Answering the unlimited-trades follow-up with the one-trade loop, or the reverse. Restate which variant you are solving before you code it.
How to explain it out loud
Fictional example
- Candidate
- I could compare each buy day with every later sell day, which is quadratic. But for any sell day, the only buy that matters is the cheapest one before it.
- Candidate
- So I walk the prices once, keeping the cheapest price so far and the best gain so far. Each day I check the gain from selling today, then lower the cheapest price if today is lower.
- Candidate
- That is linear time and constant space. On 9, 4, 11, 2, 6 the cheapest becomes 4, at 11 the gain is 7, and the later 2 only produces 4 at the end, so the answer stays 7.
Problems that build on the same idea
Carrying one summary of the past through a loop is the heart of Maximum Subarray, where the running value is the best sum ending at the current spot; in fact, the stock problem is Maximum Subarray applied to day-to-day price changes. Product of Array Except Self carries a running product in each direction instead of a running minimum, and Climbing Stairs carries the last two answers of a recurrence. Browse the rest on the coding problems hub.
Rehearse it with Natively
If you practice from a list of problems, Natively can read the one on your screen from a screenshot, on Mac or Windows, and propose an approach such as a running minimum, with code you can compare against your own attempt. It also transcribes a mock interview on your computer, so afterward you can check whether you explained why the global low is not always the right buy. More on an AI interview assistant.
Questions people ask
What is the optimal solution to Best Time to Buy and Sell Stock?
Walk the prices once, keeping the lowest price seen so far and the best gain so far. Each day, compare selling at today's price against that lowest earlier price. It runs in O(n) time with O(1) extra space.
Why not just subtract the minimum price from the maximum price?
Because the sale must come after the purchase. If the lowest price arrives after the highest one, that pair is not a legal trade, and the real answer is smaller.
What should the function return if prices only go down?
Usually 0, meaning you skip trading. Confirm it with the interviewer, since some versions want the least bad loss instead.
How do you solve the version with unlimited transactions?
Add up every positive change from one day to the next. Each rise is profit a trader holding one share at a time could capture, and the total equals the best sequence of trades.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
