Example 1
ready- Input
prices = [ 7, 1, 5, 3, 6, 4 ]- Expected
5- Why
- buy at 1, then sell later at 6
A stock chart makes hindsight look easy. Your code has to make the best legal trade without looking backwards in time.
You're given prices, where prices[i] is one share's price on day i. Choose one day
to buy and a later day to sell, then return the largest profit that trade can earn.
If every possible trade loses money or breaks even, return 0.
A few ground rules:
1 <= prices.length <= 100_0000 <= prices[i] <= 10_000Hints
Pick each buy day, pair it with every later sell day, and keep the best difference. What work gets repeated when you move to the next sell day?
If today is the sell day, only one earlier fact matters: the lowest price seen before today. A more expensive earlier purchase can never produce a better profit today.
Scan left to right. Track the cheapest price so far and the best profit so far. Check today's profit before allowing today's price to become a future purchase.
How would your state change if you were allowed to complete as many non-overlapping trades as you wanted?
Visible cases
prices = [
7,
1,
5,
3,
6,
4
]5prices = [
7,
6,
4,
3,
1
]0prices = [
2,
4,
1
]2Interview signal
The chart has many pairs of days, but each sell day has only one purchase worth remembering.
Choose every buy day and test every later sell day. A negative difference never improves
the answer, so starting best at zero handles falling prices naturally.
def max_profit(prices: list[int]) -> int:
best = 0
for buy in range(len(prices) - 1):
for sell in range(buy + 1, len(prices)):
best = max(best, prices[sell] - prices[buy])
return bestTime O(n²) — you inspect every ordered buy/sell pair. Space O(1) — only the best profit is stored.
Treat each price as today's possible sale. The best purchase for that sale is the lowest price strictly before it, so carry that minimum forward while you scan.
def max_profit(prices: list[int]) -> int:
cheapest = prices[0]
best = 0
for price in prices[1:]:
best = max(best, price - cheapest)
cheapest = min(cheapest, price)
return bestChecking profit before updating cheapest keeps the time order honest. If today's price
becomes the new minimum, it can only serve as a purchase for a later day.
The exchange argument is a proof that replacing a choice with the greedy choice can't make an answer worse. Fix any sell day in an optimal trade. If its purchase isn't the cheapest earlier day, exchange that purchase for the cheapest one; the sale stays legal and the profit can only rise. Therefore the cheapest earlier price is globally optimal for every possible sale, and taking the best of those sales is globally optimal overall.
Time O(n) — each price is visited once. Space O(1) — two numbers hold all the history you need.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
5