Choose at most one purchase and a later sale to maximize the profit from a daily price list.
Problem
Input. A list of finite integer prices in chronological day order.
Output. Return the largest achievable sale price minus purchase price, or zero if no profitable trade exists.
Rules. Buy at most once and sell on a strictly later day. There are no fees, short sales, or multiple transactions. Doing nothing is allowed. Empty and singleton lists return zero; leave the list unchanged.
Example. For prices [7, 1, 5, 3, 6, 4], return 5.
Buy at index 1 for 1 and sell at index 4 for 6.
For falling prices [7, 6, 4], return 0, not a negative forced-trade profit.
Picture
Scan [7,1,5,3,6,4] from left to right:
| Day | Price | lowest after insertion | Candidate | best |
|---|---|---|---|---|
| 0 | 7 | 7 | 0 | 0 |
| 1 | 1 | 1 | 0 | 0 |
| 2 | 5 | 1 | 4 | 4 |
| 3 | 3 | 1 | 2 | 4 |
| 4 | 6 | 1 | 5 | 5 |
| 5 | 4 | 1 | 3 | 5 |
For one fixed sale, a cheaper buy cannot reduce profit.
After each day, lowest stores the prefix minimum. The saved best stores the largest completed optional profit.
The source inserts today’s price before computing price - lowest. A new minimum produces a same-day zero, not a valid transaction.
That zero cannot improve best, which starts at zero. Every positive improvement uses a strictly earlier, lower price.
The result is five: buy on day one and sell on day four. The later price four does not erase that saved answer.
Visual low marks the current prefix minimum’s day; day marks the current candidate sale.
The underline marks the saved trade, not today’s candidate.
Problem trace
Separate example: a worse current trade does not erase the saved best
Reference drawing
Problem trace
Keep the best earlier trade even when the current day is worse
Execution trace
- low
- 0
- day
- 0
- scanned prefix
- [0..0]
- low
- 0→1
- day
- 0→1
- scanned prefix
- [0..0]→[0..1]
- day
- 1→2
- scanned prefix
- [0..1]→[0..2]
- arithmetic
- lowest=min(7,1)=1; profit=1-1=0; best=0→lowest=1; profit=5-1=4; best=4
- day
- 2→3
- scanned prefix
- [0..2]→[0..3]
- arithmetic
- lowest=1; profit=5-1=4; best=4→lowest=1; profit=3-1=2; best=4
- day
- 3→4
- scanned prefix
- [0..3]→[0..4]
- arithmetic
- lowest=1; profit=3-1=2; best=4→lowest=1; profit=6-1=5; best=5
- day
- 4→5
- scanned prefix
- [0..4]→[0..5]
- arithmetic
- lowest=1; profit=6-1=5; best=5→lowest=1; profit=4-1=3; best=5
- Recognize it
- Use a running minimum when an ordered one-pass problem asks for the best later-minus-earlier difference and the buy or baseline must occur before the current item.
- Keep true
- After each day, lowest is the minimum price in the scanned prefix and best is the largest valid sell-minus-earlier-buy profit whose selling day lies in that prefix.
- Reuse it
- For maximum ordered differences, summarize the best earlier baseline while treating each new value as the right endpoint; analogous scans find maximum rise, minimum spread, and best prefix-relative gain.
Code
def max_profit(prices: list[int]) -> int:
lowest = float("inf")
best = 0
for price in prices:
lowest = min(lowest, price)
best = max(best, price - lowest)
return best
For days, the scan uses integer operations and stored slots.
Global maximum minus global minimum fails on [7,1]: the earlier seven cannot be a later sale.
Change the Saved Result or Obligation
Start from max_profit. Two adjustable parts are the returned evidence and permission to skip trading.
-
Return a feasible witness.
New task: Return
[profit, buy, sell]for a profitable trade, orNone.Picture and change: Retain the minimum’s index. Score each sale against the strictly earlier minimum before inserting today’s price.
Code: Complete replacement:
def best_trade_days(prices): if len(prices) < 2: return None lowest, buy = prices[0], 0 best, result = 0, None for sell in range(1, len(prices)): profit = prices[sell] - lowest if profit > best: best, result = profit, [profit, buy, sell] if prices[sell] < lowest: lowest, buy = prices[sell], sell return resultCheck:
[7,1,5,3,6,4]returns[5,1,4];[3,2,1]returnsNone.Strict comparisons retain the earliest sale attaining the best profit and its earliest minimum-price buy. Time remains , with slots.
Use when: The caller needs actual, strictly ordered days rather than a scalar optimum.
-
Require exactly one trade.
New task: Return the best profit even when every possible trade loses money.
Picture and change: Remove no-trade zero. Initialize
bestfrom the first valid pair and score before updatinglowest.Code: Complete replacement; fewer than two days returns
None.def mandatory_trade_profit(prices): if len(prices) < 2: return None lowest, best = prices[0], prices[1] - prices[0] for sell in range(1, len(prices)): best = max(best, prices[sell] - lowest) lowest = min(lowest, prices[sell]) return bestCheck:
[7,5,1]returns-2, while the optional reference returns zero. A singleton returnsNone.Inserting the current day first would introduce an illegal same-day zero. Initializing
best = 0would also hide every loss.Use when: Skipping the action is forbidden. Time remains , with slots.
Rebuild Eligibility
How would a minimum waiting period change the stored minimum?
Answer: Admit a buy day only when it is old enough for the current sale. The minimum’s role stays unchanged.
Multiple trades, fees, cooldowns, and short selling need separately derived state. This deterministic array task makes no market forecast.