Optimal Single Buy-and-Sell Gain
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an integer list prices where prices[i] records an asset's price on day i, implement max_profit(prices) to return the largest net gain obtainable from at most one round-trip trade: purchasing a single unit on day b and selling it on a strictly later day s (0 <= b < s < len(prices)), earning prices[s] - prices[b].
Making zero trades is allowed and earns 0. Whenever no later day beats an earlier buy price (such as a single-day schedule or a non-increasing sequence), return 0.
Examples
Example 1
Input: prices = [9, 3, 7, 4, 10, 6]
Output: 7
Walk-through: Purchasing on day 1 at 3 and selling on day 4 at 10 yields 10 - 3 = 7, the highest single-trade gain available.
Example 2
Input: prices = [12, 9, 8, 5, 2]
Output: 0
Walk-through: Every subsequent day is cheaper than every prior day, so any trade loses money; doing zero trades returns 0.
Example 3
Input: prices = [6, 9]
Output: 3
Walk-through: Purchasing on day 0 at 6 and selling on day 1 at 9 earns 9 - 6 = 3.
Example 4
Input: prices = [5, 11, 2, 8, 1, 9]
Output: 8
Walk-through: Early rebound 5 -> 11 earns 6 and mid-schedule rebound 2 -> 8 also earns 6, whereas waiting for day 4's low of 1 and selling on day 5 at 9 earns 9 - 1 = 8.
Constraints
1 <= len(prices) <= 2 * 10^5-10^9 <= prices[i] <= 10^9
Step-by-step walkthrough
Understand the goal and rules
We are given a list
priceswhereprices[i]is the daily price on dayi. We want the largest gain obtainable from at most one trade: buying on some daybuyand selling on a strictly later daysell > buy, earningprices[sell] - prices[buy].Two rules shape the entire algorithm:
- Time moves one way (
buy < sell). We cannot simply computemax(prices) - min(prices), because the lowest price might appear after the highest price. On[3, 8, 1, 2],8 - 1 = 7is invalid because8occurred before1; the best valid trade buys at3and sells at8for5. - Zero trades is allowed. On a single-day schedule or a sequence that never rises (such as
[12, 9, 8, 5, 2]), every trade loses or makes0, so we skip trading and return0. The result is never negative.
- Time moves one way (
Start with brute force and see why it is slow
The most direct check tries every valid
(buy, sell)pair withbuy < selland tracks the largest gain above0:def brute_max_profit(prices): 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_profitAcross
ndays, there aren * (n - 1) / 2pairs. Atn = 200,000, that is roughly 20 billion subtractions — far too slow. Notice why it repeats work: for each sell day, the inner loop re-scans the past from scratch to find the cheapest earlier buy day.Key insight: track the cheapest earlier buy day
Flip your viewpoint and ask: Suppose I sell on day
day. Which earlier day should I have bought on?To maximize
prices[day] - prices[buy]across allbuy < day,prices[buy]should be as small as possible. No other past price matters — only the minimum price seen across days0throughday - 1.Day index: 0 1 2 3 4 5 Price: 9 3 7 4 10 6 ^ ^ cheapest past sell here: buy = 3 10 - 3 = 7 (best!)Advancing from
daytoday + 1updates that running minimum with a single comparison:min(old_min, prices[day]). That turns an O(n) lookback per day into O(1) work!Write the single-pass loop
Maintain two integers while scanning
day = 1throughlen(prices) - 1:min_buy_price: lowest price seen on strictly earlier days (0 .. day - 1), initialized toprices[0].best_profit: highest gain found so far, initialized to0(representing zero trades).
Two implementation details keep the code clean and O(1)-space:
- Loop with
for day in range(1, len(prices)):instead offor price in prices[1:]:, because slicingprices[1:]in Python copiesn - 1elements and uses O(n) extra memory rather than O(1). - Compute
profit_today = sell_price - min_buy_pricebefore updatingmin_buy_price, guaranteeingmin_buy_pricealways comes from a strictly earlier day.
def max_profit(prices: List[int]) -> int: if not prices: return 0 # min_buy_price: int — lowest stock price seen on any strictly earlier day (days 0 .. day - 1) min_buy_price = prices[0] # best_profit: int — highest profit achievable so far; starts at 0 because doing 0 trades is allowed best_profit = 0 # Phase 1: scan each potential sell day from day 1 onward (avoid slicing prices[1:] to keep O(1) space) for day in range(1, len(prices)): sell_price = prices[day] # Phase 2: check the profit if we bought at the cheapest earlier day and sold today profit_today = sell_price - min_buy_price if profit_today > best_profit: best_profit = profit_today # Phase 3: update min_buy_price AFTER checking today's sale so we never buy and sell on the same day if sell_price < min_buy_price: min_buy_price = sell_price return best_profitTrace through concrete examples
Let's trace Example 1,
prices = [9, 3, 7, 4, 10, 6]. Before the loop starts,min_buy_price = 9(day 0) andbest_profit = 0:day | sell_price | min_buy_price (before) | profit_today | best_profit | min_buy_price (after) ----+------------+------------------------+--------------+-------------+---------------------- 1 | 3 | 9 | 3 - 9 = -6 | 0 | 3 2 | 7 | 3 | 7 - 3 = 4 | 4 | 3 3 | 4 | 3 | 4 - 3 = 1 | 4 | 3 4 | 10 | 3 | 10 - 3 = 7 | 7 | 3 5 | 6 | 3 | 6 - 3 = 3 | 7 | 3The loop finishes and returns
7(buy on day 1 at3, sell on day 4 at10).On Example 2,
prices = [12, 9, 8, 5, 2], every day is belowmin_buy_price, soprofit_todayis negative on every iteration,best_profitstays0, and we return0.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_profit(prices: List[int]) -> int: if not prices: return 0 # min_buy_price: int — lowest stock price seen on any strictly earlier day (days 0 .. day - 1) min_buy_price = prices[0] # best_profit: int — highest profit achievable so far; starts at 0 because doing 0 trades is allowed best_profit = 0 # Phase 1: scan each potential sell day from day 1 onward (avoid slicing prices[1:] to keep O(1) space) for day in range(1, len(prices)): sell_price = prices[day] # Phase 2: check the profit if we bought at the cheapest earlier day and sold today profit_today = sell_price - min_buy_price if profit_today > best_profit: best_profit = profit_today # Phase 3: update min_buy_price AFTER checking today's sale so we never buy and sell on the same day if sell_price < min_buy_price: min_buy_price = sell_price return best_profit✅ Submit now — all tests should pass.
Intuition & how it works
Imagine stepping forward through a calendar of daily prices while carrying a single sticky note. On that sticky note, you keep the cheapest price seen on any earlier day. Each time you step onto a new day, you ask one question: "If I had bought at the price on my sticky note and sold today, would that beat my best gain so far?" After checking, if today's price is even cheaper than what is written on the note, you update the note with today's price for future days to use.
The brute-force approach checks every (buy, sell) pair of days with nested loops, repeating the search for the cheapest past day over and over in O(n^2) time. Another tempting shortcut — returning max(prices) - min(prices) — fails whenever the global minimum occurs after the global maximum, which would sell before buying. Maintaining a prefix minimum (a running minimum of all elements from index 0 up to the previous index) supplies the exact optimal buy price for every candidate sell day in constant time.
Let's walk through a 4-day trace, prices = [8, 2, 7, 4]:
- Start after day 0:
min_buy_price = 8,best_profit = 0. - Day 1 (
price = 2): selling today gives2 - 8 = -6(below0), then2 < 8updatesmin_buy_priceto2. - Day 2 (
price = 7): selling today gives7 - 2 = 5, updatingbest_profitto5;min_buy_pricestays2. - Day 3 (
price = 4): selling today gives4 - 2 = 2(below5), and4is not below2. Returnbest_profit = 5.
Complexity
- Time: O(n), where
nislen(prices). We visit each day from index1ton - 1once and perform a single subtraction and two comparisons per day. - Space: O(1) auxiliary space. Regardless of how long
pricesis, we store only a fixed set of integer variables (min_buy_price,best_profit,day,sell_price,profit_today) and iterate by index rather than slicing the list.
Edge cases
- Single day (
[5]):range(1, 1)is empty, so no sell day exists and the function immediately returns0. - Strictly decreasing or flat prices (
[12, 9, 8, 5, 2],[3, 3, 3]): every candidate trade yields a negative or zero difference, sobest_profitremains0. - Global minimum after global maximum (
[3, 8, 1, 2]):8seesmin_buy_price = 3(gain5), and only later doesmin_buy_pricedrop to1(giving2 - 1 = 1on the final day), so5wins instead of8 - 1 = 7. - Late dip with an even larger rebound (
[5, 11, 2, 8, 1, 9]):best_profitfirst reaches11 - 5 = 6, thenmin_buy_pricedrops to2and later1, allowing day 5 to reach9 - 1 = 8. - Negative values (
[-5, -2, -10, -1]): subtraction measures exact gain (-1 - (-10) = 9), and all-decreasing negatives like[-2, -5, -9]still return0.
Common mistakes
- Returning
max(prices) - min(prices): ignores chronological order and pairs an early peak with a later trough. - Initializing
best_profitto-inforprices[1] - prices[0]: returns a negative number on falling schedules when zero trades (0gain) is allowed, and indexingprices[1]crashes on a 1-element list. - Writing
for price in prices[1:]:while claiming O(1) space: list slicing in Python copiesn - 1elements into a new list, quietly using O(n) extra memory. - Resetting
best_profitwhenmin_buy_priceupdates: a lower buy price found late in the array might never be followed by a high sell price (as in[3, 8, 1, 2]), so earlier gains must stay recorded.
Alternative approaches
- Kadane's algorithm on daily price changes: Kadane's algorithm is a single-pass method that finds the contiguous subarray with the largest sum by resetting a running total to
0whenever it dips below0. Sinceprices[sell] - prices[buy]equals the telescoping sum of daily changes(prices[buy + 1] - prices[buy]) + ... + (prices[sell] - prices[sell - 1]), running Kadane's algorithm on adjacent differences produces the exact same O(n) time and O(1) space result. - Right-to-left suffix maximum scan: A suffix maximum is the largest value from a given index through the end of the array. Scanning backward while tracking the highest future sell price seen so far and testing each day as a buy day is symmetric and also runs in O(n) time and O(1) space.
Follow-up questions
- How would you return the buy and sell day indices that achieve the maximum gain instead of only the gain value? Track
min_buy_day = 0alongsidemin_buy_price, updatingmin_buy_day = daywheneversell_price < min_buy_price. Wheneverprofit_today > best_profit, savebest_pair = (min_buy_day, day). Ifbest_profitremains0, returnNone(or(-1, -1)per the caller's convention), all in O(n) time and O(1) space. - How does the algorithm change if you may execute unlimited non-overlapping trades while holding at most one share at any time? Every multi-day rise from day
ito dayjequals the sum of the single-day changes in between, so collecting every positive adjacent differencemax(0, prices[day] - prices[day - 1])earns at least as much as any set of non-overlapping trades. Summing all positive daily steps solves it in O(n) time and O(1) space. - What if you are capped at most k buy-sell transactions across the entire schedule? Use dynamic programming — breaking the problem into overlapping subproblems and updating best-so-far balances day by day — keeping two arrays of length
k + 1:best_hold[t](highest cash balance while holding a unit during tradet) andbest_sold[t](highest cash balance after completingttrades). Each day updates allkstates in O(k) work, running in O(n * k) time and O(k) space (or reducing immediately to the O(n) unlimited-trades pass wheneverk >= n // 2).
Follow-up questions
- How would you return the buy and sell day indices that achieve the maximum gain instead of only the gain value?
- How does the algorithm change if you may execute unlimited non-overlapping trades while holding at most one share at any time?
- What if you are capped at most k buy-sell transactions across the entire schedule?
Similar questions
- Distributed 64-Bit Key Generator and Multi-Level Parking System
- 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