Optimal Gain from a Single Share Transaction
Medium · Coding & Algorithms · Backend Engineer · Onsite
Problem Statement
Given an integer list prices where prices[i] records the price of one share on day i (0-indexed), compute the largest net gain obtainable from at most one trade.
A valid trade buys a single share on some day b and sells that share on a strictly later day s (0 <= b < s < len(prices)), earning prices[s] - prices[b]. Buying and selling on the same day is not allowed, and selling cannot happen before buying. If every valid pair of days breaks even or loses money—or if fewer than two days exist—do not trade and return 0.
def max_profit(prices: List[int]) -> int:
Examples
Example 1
Input: prices = [9, 3, 7, 4, 10, 6]
Output: 7
Purchasing on day 1 at 3 and selling on day 4 at 10 earns 10 - 3 = 7. Although 9 appears on day 0, you cannot sell at 9 and buy later at 3 because the purchase day must precede the sale day.
Example 2
Input: prices = [12, 9, 8, 5, 2]
Output: 0
Quotes drop every day, so every legal (buy, sell) pair has prices[sell] < prices[buy]. Skipping the trade yields 0.
Constraints
1 <= len(prices) <= 10^50 <= prices[i] <= 10^9
Step-by-step walkthrough
Understand the time-order rule
We are given daily share quotes
prices[0 .. n - 1]. We may choose at most one indexbuyto purchase a share and a strictly later indexsell > buyto sell it, earningprices[sell] - prices[buy]. Whenever every legal pair loses money (orpriceshas length1), we skip trading and return0.Why can't we just return
max(prices) - min(prices)? Because time only moves forward — you cannot sell on day0and buy on day1:prices = [9, 3, 7, 4, 10, 6] Price 10 | * <-- Sell on Day 4 at 10 (gain = 10 - 3 = 7) 9 | * (Day 0 quote comes BEFORE Day 1's dip) 7 | * 6 | * 4 | * 3 | * <-------------- Buy on Day 1 at 3 +------------------------ 0 1 2 3 4 5 DayWith up to
100,000days and quotes up to10^9, we want a singleO(n)pass that enforcesbuy < sell.Brute force: check every `(buy, sell)` pair
The most direct way to obey
buy < sellis to test every possible buy day against every later sell day:def max_profit_brute(prices: list[int]) -> int: best = 0 for buy in range(len(prices)): for sell in range(buy + 1, len(prices)): profit = prices[sell] - prices[buy] if profit > best: best = profit return bestThis checks
n * (n - 1) / 2pairs. Atn = 100,000, that is roughly5 * 10^9subtractions — accurate for short lists, but far too slow for the full constraint. Notice why it repeats work: for eachsellday, it rescans all earlier days from scratch just to rediscover which earlier day was cheapest.Key idea: fix the sell day and track the cheapest past buy day
Flip the perspective from choosing the buy day first to evaluating each sell day as we walk forward:
If we sell on
day(forday >= 1), which earlier index0 .. day - 1gives the best purchase price?Since
prices[day]is fixed,prices[day] - prices[buy]is largest whenprices[buy]is as small as possible:Best gain when selling on `day` = prices[day] - min(prices[0 .. day - 1])That prefix minimum does not need to be recomputed from scratch. As we advance one day at a time, we carry a single running variable
lowest_buy_price:- Before inspecting
day,lowest_buy_pricealready equalsmin(prices[0 .. day - 1]). - After checking the gain of selling on
day, we updatelowest_buy_price = min(lowest_buy_price, prices[day])so it is ready forday + 1.
- Before inspecting
Code the single left-to-right pass
We initialize: -
lowest_buy_price = prices[0](day0is the only candidate buy day before day1), -best_profit = 0(making zero trades is always allowed).Then we loop
dayfrom1tolen(prices) - 1. Notice two clean properties of this loop: 1. Single-day lists (len(prices) == 1):range(1, 1)executes zero iterations and returns0, matching the rule that buying and selling require two distinct days. 2. Update order inside the loop: We computeprofit_if_sold_todaybefore foldingtoday_priceintolowest_buy_price. That guarantees a share is never bought and sold on the exact same day (which also keeps the logic bug-free if a variant ever requires making a trade even at a loss).from typing import Any, Dict, List, Optional, Set, Tuple def max_profit(prices: List[int]) -> int: # lowest_buy_price: minimum stock price seen across all earlier days 0 .. day - 1 lowest_buy_price = prices[0] # best_profit: highest profit from one valid buy-then-sell trade (0 = skip trading) best_profit = 0 # Start on day 1 because selling requires a strictly earlier buy day. for day in range(1, len(prices)): today_price = prices[day] # Phase 1: Best profit if we sell today is today's price minus the cheapest past day. profit_if_sold_today = today_price - lowest_buy_price if profit_if_sold_today > best_profit: best_profit = profit_if_sold_today # Phase 2: Only after checking today's sale can today become a buy option for future days. if today_price < lowest_buy_price: lowest_buy_price = today_price return best_profitTrace Examples 1 and 2 day by day
Example 1:
prices = [9, 3, 7, 4, 10, 6](starts withlowest_buy_price = 9,best_profit = 0)day today_price lowest_buy_price (before) profit_if_sold_today best_profit lowest_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 3Returned answer:
7(buy at3on day1, sell at10on day4).Example 2:
prices = [12, 9, 8, 5, 2](starts withlowest_buy_price = 12,best_profit = 0)day today_price lowest_buy_price (before) profit_if_sold_today best_profit lowest_buy_price (after) -------------------------------------------------------------------------------------------------------- 1 9 12 9 - 12 = -3 0 9 2 8 9 8 - 9 = -1 0 8 3 5 8 5 - 8 = -3 0 5 4 2 5 2 - 5 = -3 0 2Every
profit_if_sold_todayis negative, sobest_profitstays0.Full solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_profit(prices: List[int]) -> int: # lowest_buy_price: minimum stock price seen across all earlier days 0 .. day - 1 lowest_buy_price = prices[0] # best_profit: highest profit from one valid buy-then-sell trade (0 = skip trading) best_profit = 0 # Start on day 1 because selling requires a strictly earlier buy day. for day in range(1, len(prices)): today_price = prices[day] # Phase 1: Best profit if we sell today is today's price minus the cheapest past day. profit_if_sold_today = today_price - lowest_buy_price if profit_if_sold_today > best_profit: best_profit = profit_if_sold_today # Phase 2: Only after checking today's sale can today become a buy option for future days. if today_price < lowest_buy_price: lowest_buy_price = today_price return best_profit✅ Submit now — all tests should pass.
Intuition & how it works
Imagine flipping through a ledger of daily share quotes one page at a time while keeping a single sticky note with the cheapest quote seen on any earlier page. Each time you turn to a new day, you ask one simple question: "If I had bought on that cheapest earlier day and sold today, how much would I clear?" By tracking both that cheapest earlier quote (lowest_buy_price) and the best gain seen so far (best_profit, initialized to 0 since sitting out costs nothing), a single left-to-right pass evaluates the optimal buy day for every candidate sell day.
Simply computing max(prices) - min(prices) fails whenever the peak appears before the trough, because you cannot sell a share before buying it. Locking onto the overall minimum quote and only checking days after it also fails (for example, in [2, 9, 1, 4], buying at 2 and selling at 9 earns 7, whereas waiting for the global low 1 only earns 3). Testing every (buy, sell) pair with two nested loops is exact, but across 100,000 days it performs roughly 5 billion subtractions and times out.
Trace prices = [8, 3, 7, 2]. Before the loop, Day 0 sets lowest_buy_price = 8 and best_profit = 0. On Day 1 (price = 3), selling today yields 3 - 8 = -5 (best_profit stays 0), and lowest_buy_price drops to 3. On Day 2 (price = 7), selling today yields 7 - 3 = 4, raising best_profit to 4 while lowest_buy_price stays 3. On Day 3 (price = 2), selling today yields 2 - 3 = -1 (best_profit stays 4) and lowest_buy_price drops to 2 — then the loop ends and returns 4.
Complexity
Let n = len(prices) be the number of days.
- Time: O(n). Starting at index
1, we inspect each of then - 1remaining quotes once and perform one subtraction plus two comparisons (O(1)work) per day. - Space: O(1). Whether
pricesholds1quote or100,000quotes, we store only four scalar integer variables (lowest_buy_price,best_profit,today_price, andprofit_if_sold_today).
Edge cases
- Single day (
len(prices) == 1):range(1, 1)runs zero iterations and immediately returns0, since no later sell day exists. - Strictly decreasing quotes (
[12, 9, 8, 5, 2]): Everyprofit_if_sold_todayis negative, sobest_profitstays0. - Flat quotes (
[4, 4, 4, 4]): Every trade earns0, returning0. - Peak before trough (
[3, 8, 1, 2]): Returns8 - 3 = 5rather than8 - 1 = 7, becauselowest_buy_priceonly summarizes earlier days. - Best trade ignores the global minimum (
[2, 9, 1, 4]):best_profitrecords9 - 2 = 7on Day1and preserves it even afterlowest_buy_pricedrops to1on Day2. - Extreme quote bounds (
0and10^9):[0, 10**9]yields10^9, fitting comfortably in standard signed 32-bit and Python integers.
Common mistakes
- Computing
max(prices) - min(prices): Violatesbuy < sellwhenever a high quote precedes the cheapest dip, such as[12, 9, 8, 5, 2]or[3, 8, 1, 2]. - Finding
argmin(prices)first and scanning only to its right: Misses larger gains that finish before the global minimum arrives, such as[2, 9, 1, 4]. - Initializing
best_profittofloat('-inf')orprices[1] - prices[0]: Returns a negative value on falling quotes instead of0(andprices[1]raisesIndexErrorwhenlen(prices) == 1). - Updating
lowest_buy_pricebefore computingprofit_if_sold_today: Permits a phantom same-day buy-and-sell of0— harmless whenbest_profitstarts at0, but buggy if a variant forces a trade on falling markets.
Alternative approaches
- Kadane's algorithm on day-to-day changes: Because
prices[sell] - prices[buy]equals the telescoping sum(prices[buy + 1] - prices[buy]) + ... + (prices[sell] - prices[sell - 1]), the problem is equivalent to finding the maximum subarray sum (the contiguous slice of numbers with the largest total) of daily differences via Kadane's algorithm — scanning left to right while clamping any negative running sum back to0— in the sameO(n)time andO(1)space.
Follow-up questions
- How would you extend the algorithm when up to two non-overlapping buy-sell trades are permitted? Maintain four best-so-far cash balances as each quote
parrives:after_buy1(highest balance after buying the first share, starting at-prices[0]),after_sell1(after selling the first share,0),after_buy2(after reinvestingafter_sell1into a second share,-prices[0]), andafter_sell2(after selling the second share,0). Updatingafter_buy1 = max(after_buy1, -p),after_sell1 = max(after_sell1, after_buy1 + p),after_buy2 = max(after_buy2, after_sell1 - p), andafter_sell2 = max(after_sell2, after_buy2 + p)solves the two-trade problem inO(n)time andO(1)space. - What changes if selling a share always deducts a constant brokerage fee? When you are still capped at one trade, every trade pays the same
fee, so the optimal pair of days never changes and the answer ismax(0, max_profit(prices) - fee). When unlimited sequential trades are allowed withfeeper sale, track two running states —cash(best balance holding zero shares, initialized to0) andhold(best balance holding one share, initialized to-prices[0]) — and updatecash, hold = max(cash, hold + p - fee), max(hold, cash - p)inO(n)time andO(1)space. - How would you maintain the best achievable gain in real time over an unbounded live tick feed? An online algorithm processes each arriving item immediately without knowing future inputs or keeping the entire history in memory. Our one-pass loop is already online: store only
lowest_buy_priceandbest_profit, update both inO(1)time per incoming quote, and answer queries inO(1)time usingO(1)space forever. (If trades must instead fall inside a sliding window of the latestWticks, old minimums expire, so you can maintain a fixed-capacity segment tree over the lastWticks storing(min_price, max_price, best_gain)per node forO(log W)updates.)
Follow-up questions
- How would you extend the algorithm when up to two non-overlapping buy-sell trades are permitted?
- What changes if selling a share always deducts a constant brokerage fee?
- How would you maintain the best achievable gain in real time over an unbounded live tick feed?
Similar questions
- Increment Fixed-Size Digit Array by One
- Square Root Approximation Without Built-In Exponents
- Validate Nesting of Three Bracket Types
- Distinct Phrase Variations via Anagram Substitution
- Count Enclosed Islands
- Interior Land Islands in a Binary Matrix
More Oracle interview questions
- Point-in-Time Lookups in a Versioned Key Store Medium
- System Architecture Walkthrough: End-to-End Topology, Trade-Offs, and Business Value Medium
- Total Island Count and Maximum Island Area Medium Pro
- Distributed L4/L7 Load Balancer Medium Pro
- All Lexicographical Down-Right Routes in an Obstacle Grid Medium Pro
- Fixed-TTL Key-Value Store with Renewal and Active Count Easy Pro
- Maximum Rating Sum Without Consecutive Skips Medium Pro
- Largest Minimum Across Fixed-Length Subarrays Medium Pro
- Fewest Rooms for Concurrent Meetings Medium Pro
- Object-Oriented Fixed-Capacity LRU Cache in Constant Time Medium Pro