Best Single-Trade Stock Gain
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given a list of non-negative integers prices, where prices[d] denotes the market quote of a single share on day d (0-indexed), determine the largest net gain obtainable from at most one trade.
A valid trade consists of purchasing one share on some day buy and selling that share on a strictly later day sell (0 <= buy < sell < len(prices)), earning prices[sell] - prices[buy]. If every valid pair of days yields zero or negative gain—or if fewer than two days exist—skip trading altogether and return 0.
def max_profit(prices: List[int]) -> int:
Examples
Example 1
Input: prices = [9, 3, 7, 2, 10, 5]
Output: 8
Buying on day 3 at 2 and selling on day 4 at 10 earns 10 - 2 = 8. An earlier trade from day 1 (3) to day 2 (7) only earns 4, and the opening quote of 9 on day 0 cannot be used as a sale price for any later purchase.
Example 2
Input: prices = [12, 10, 8, 8, 3]
Output: 0
Quotes never rise above an earlier day's level, so any purchase followed by a later sale either breaks even (8 - 8 = 0) or loses money. Making no trade yields 0.
Constraints
1 <= len(prices) <= 10^50 <= prices[d] <= 10^4
Step-by-step walkthrough
Restate the problem
We receive a list
priceswhereprices[day]gives the share quote onday. We may purchase one share on some indexbuyand sell it on a strictly later indexsell(buy < sell). We want to return the largest possible gainprices[sell] - prices[buy], or0when every legal trade breaks even or loses money.Because time moves forward,
max(prices) - min(prices)does not work whenever the peak comes before the trough (for instance,[9, 2, 6, 1]has9 - 1 = 8, yet the best chronological trade buys at2and sells at6for4).Brute force first and why it is too slow
A direct nested scan pairs every buy index with every subsequent sell index:
def max_profit_brute(prices: list[int]) -> int: best_profit = 0 for buy in range(len(prices)): for sell in range(buy + 1, len(prices)): profit = prices[sell] - prices[buy] if profit > best_profit: best_profit = profit return best_profitChecking
n * (n - 1) / 2day pairs requires around5 * 10^9iterations atn = 10^5, which is far too slow. Notice the repeated effort: for every candidate sell day, the inner loop re-scans the entire prefix just to rediscover the cheapest historical quote.Key idea: fix the sell day and remember the lowest quote so far
Turn the question around: if we sell on
day, which earlier day0 .. day - 1would have been the best day to buy? Always the cheapest earlier day, since subtracting the smallest prior quote maximizesprices[day] - min_price_so_far.Rather than re-scanning earlier days from scratch, we carry
min_price_so_farforward in a single left-to-right pass:prices: [ 9, 3, 7, 2, 10, 5 ] day index: 0 1 2 3 4 5 min_price_so_far: 9 -> 3 -> 3 -> 2 -> 2 -> 2 sell today profit: - -6 +4 -1 +8 +3 best_profit: 0 0 4 4 8 8For each
dayfrom1throughlen(prices) - 1: 1. Evaluateprofit_if_sold_today = prices[day] - min_price_so_farand raisebest_profitif we beat our best gain. 2. Lowermin_price_so_farwhenprices[day]sets a new historical low for future selling days.Trace Example 1 and Example 2
Let's walk through Example 1,
prices = [9, 3, 7, 2, 10, 5]:Start (day 0): min_price_so_far = 9, best_profit = 0 day 1 (price = 3): profit_if_sold_today = 3 - 9 = -6 -> best_profit stays 0 3 < 9 -> min_price_so_far becomes 3 day 2 (price = 7): profit_if_sold_today = 7 - 3 = 4 -> best_profit becomes 4 7 < 3 is False -> min_price_so_far stays 3 day 3 (price = 2): profit_if_sold_today = 2 - 3 = -1 -> best_profit stays 4 2 < 3 -> min_price_so_far becomes 2 day 4 (price = 10): profit_if_sold_today = 10 - 2 = 8 -> best_profit becomes 8 10 < 2 is False -> min_price_so_far stays 2 day 5 (price = 5): profit_if_sold_today = 5 - 2 = 3 -> best_profit stays 8 5 < 2 is False -> min_price_so_far stays 2 Return best_profit = 8 (bought at 2 on index 3, sold at 10 on index 4).On Example 2,
prices = [12, 10, 8, 8, 3],profit_if_sold_todaytakes values-2, -2, 0, -5across days1..4, sobest_profitstays at its initial0(representing no trade).Complete solution
Day
0has no prior day to buy from, so we seedmin_price_so_far = prices[0]and sweep fromday = 1onward:from typing import Any, Dict, List, Optional, Set, Tuple def max_profit(prices: List[int]) -> int: # min_price_so_far: lowest stock price seen on any earlier day in prices[0..day - 1] min_price_so_far = prices[0] # best_profit: highest profit found so far; starts at 0 because skipping all trades gives 0 best_profit = 0 # Sweep from day 1 onward, treating each day as a candidate selling day for day in range(1, len(prices)): today_price = prices[day] profit_if_sold_today = today_price - min_price_so_far # Check profit before updating min_price_so_far so the buy day is strictly before today if profit_if_sold_today > best_profit: best_profit = profit_if_sold_today # Record a new historical low if today is cheaper for future selling days if today_price < min_price_so_far: min_price_so_far = today_price return best_profit✅ Submit now — all tests should pass.
Intuition & how it works
Imagine walking forward through a historical quote chart while holding a sticky note with the lowest quote seen on any earlier day. Each morning, before updating the sticky note, you ask one question: "If I had bought on that cheapest past day and sold right now, how much would I earn?" Afterward, if today's quote beats the low on your note, you write today's number down for tomorrow and beyond. Tracking that running low in one left-to-right pass is a prefix-minimum sweep (maintaining the smallest element of prices[0..day - 1] incrementally as day advances).
Why do obvious shortcuts fail? Checking every (buy, sell) pair with nested loops inspects roughly n^2 / 2 pairs — around 5 billion steps at n = 100,000 — because it searches the past from scratch on every sell day. Meanwhile, taking max(prices) - min(prices) ignores time order and gives wrong answers whenever the peak precedes the valley or the overall minimum lands near the end after a larger earlier rally.
Here is a 4-day walkthrough where the global low arrives too late, prices = [2, 9, 1, 3]:
day 0 (price 2): seed min_price_so_far = 2, best_profit = 0
day 1 (price 9): sell today -> 9 - 2 = 7 -> best_profit = 7; min stays 2
day 2 (price 1): sell today -> 1 - 2 = -1; new low! min_price_so_far = 1
day 3 (price 3): sell today -> 3 - 1 = 2 (less than 7); min stays 1
Result: 7 (bought at 2, sold at 9 — even though 1 was the overall minimum!).
Complexity
- Time:
O(n), wherenislen(prices). We visit each index from1ton - 1once and do a constant number of comparisons and subtractions (O(1)work) per element. - Space:
O(1)auxiliary space. Only four scalar variables (min_price_so_far,best_profit,today_price, andprofit_if_sold_today) are kept in memory, with no extra lists or slices allocated.
Edge cases
- Single-day input (
[5]or[0]): Buying and selling require two distinct days;range(1, 1)is empty, so the loop does not run and0is returned. - Non-increasing or constant quotes (
[12, 10, 8, 8, 3],[4, 4, 4]): Everyprofit_if_sold_todayis<= 0, leavingbest_profitat0. - Optimal buy is not the global low (
[2, 9, 1, 3]): Buying at2and selling at9yields7, whereas buying at the later global low1only yields3 - 1 = 2. Testing every day against the running prefix low captures both early and late rallies. - Zero-priced shares (
[0, 10000]): Quotes down to0are permitted by the constraints; buying at0and selling at10000cleanly returns10000.
Common mistakes
- Computing
max(prices) - min(prices): That sells before buying whenever the highest quote appears before the lowest quote (returning8instead of4on[9, 2, 6, 1]). - Only scanning to the right of
min(prices): Locating the global minimum first and taking the highest value after it misses bigger gains that happened before the global low (returning2instead of7on[2, 9, 1, 3]). - Seeding
best_profitwithfloat("-inf")orprices[1] - prices[0]: On falling inputs such as[12, 10, 8, 8, 3], that returns a negative number instead of0. - Looping over a slice
prices[1:]: In Python,prices[1:]copiesn - 1elements into a new list, silently turningO(1)auxiliary space intoO(n). Indexing viarange(1, len(prices))keeps extra memory constant.
Alternative approaches
- Kadane's algorithm on day-to-day differences: Any trade gain
prices[sell] - prices[buy]equals the telescoping sum of daily steps(prices[buy + 1] - prices[buy]) + ... + (prices[sell] - prices[sell - 1]). Computing the maximum subarray sum (the contiguous slice of daily changes with the largest total, clamped at0, known as Kadane's algorithm) achieves the sameO(n)time andO(1)space. - Right-to-left suffix-maximum pass: Sweep backward from the final day while tracking
max_future_priceto the right, testing each day as a candidate purchase day (max_future_price - prices[day]).
Follow-up questions
- Suppose you may execute unlimited buy-sell cycles while holding at most one share at any time—how does the algorithm change? Add every positive day-over-day increase
max(0, prices[d] - prices[d - 1])acrossd = 1 .. n - 1inO(n)time andO(1)space. Because any multi-day rally such as2 -> 5 -> 9(9 - 2 = 7) equals the sum of its upward daily steps(5 - 2) + (9 - 5) = 3 + 4 = 7, summing every upward step captures all profitable swings without holding through dips. - How would you adapt a multi-trade strategy if selling a share enforces a one-day rest period before your next purchase? Use dynamic programming (maintaining optimal values across a small set of states step by step) with three scalar balances per day:
holding(best cash balance while owning a share),just_sold(best cash balance after selling today), andready(best cash balance while flat and eligible to buy). Updatingholding, just_sold, ready = max(holding, ready - price), holding + price, max(ready, just_sold)for each quote solves the problem inO(n)time andO(1)space. - What additional state is needed to output the (buy_day, sell_day) index pair rather than just the profit? Store
min_day = 0(the index wheremin_price_so_faroccurred) alongsidebest_profit = 0andbest_days = None. Wheneverprices[day] - prices[min_day] > best_profit, update bothbest_profitandbest_days = (min_day, day), and wheneverprices[day] < prices[min_day], setmin_day = day; ifbest_daysremainsNoneat the end, no profitable trade exists.
Follow-up questions
- Suppose you may execute unlimited buy-sell cycles while holding at most one share at any time—how does the algorithm change?
- How would you adapt a multi-trade strategy if selling a share enforces a one-day rest period before your next purchase?
- What additional state is needed to output the (buy_day, sell_day) index pair rather than just the profit?
Similar questions
- Unpaired Value in a Sorted Array
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One