Single Buy-Sell Stock Gain
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Tests finding the maximum profit from one purchase and one sale in a price sequence using a single-pass greedy approach.
Problem Statement
Given a sequence of daily stock prices, determine the largest gain achievable by purchasing on one day and selling on a strictly later day. If no positive gain is possible, return 0.
You receive an array prices where each element represents the stock price on a particular day (indexed from 0 onward). Your task is to identify the optimal pair of days—one to buy and one to sell—such that the sell day comes after the buy day and the difference is maximized.
Constraints
1 <= len(prices) <= 10^50 <= prices[i] <= 10^4
Notes
- You must buy before you sell (the buy index must be strictly less than the sell index).
- If the prices never increase (e.g., they are flat or declining), no profitable transaction exists; return 0.
- You may perform at most one transaction (one buy followed by one sell).
Examples
Example 1
Input: single_transaction_profit([7, 1, 5, 3, 6, 4])
Output: 5
Example 2
Input: single_transaction_profit([7, 6, 4, 3, 1])
Output: 0
Hints
Hint 1
For each potential sell day, what is the best day to have bought? You don't need to remember every earlier price.
Hint 2
Track the lowest price encountered so far as you scan left to right. This represents your best buying opportunity up to the current day.
Hint 3
A single pass with two variables—minimum price seen and maximum profit found—is sufficient to solve this in O(n) time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The brute-force method examines every possible buy-sell pair (i, j) where i < j, computing prices[j] - prices[i] for each and taking the maximum. This requires O(n²) time, which is too slow for inputs up to 10⁵ elements.
A better insight: for each potential sell day, the optimal buy day is simply the day with the lowest price before it. Rather than checking all earlier days, we only need to remember the minimum price encountered so far as we scan from left to right.
We maintain two values during a single pass:
min_price: the smallest price seen up to the current day (the best buying opportunity so far).best_profit: the largest gain recorded by treating any day as a sell day and usingmin_priceas the buy price.
On each day, we do one of two things:
- If the current price is lower than
min_price, we updatemin_price. We do not compute profit here because selling at a new minimum would yield zero or negative gain compared to earlier opportunities. - Otherwise, we treat the current day as a potential sell day and compute
price - min_price, updatingbest_profitif this gain is larger.
Starting best_profit at 0 automatically handles cases where no positive gain exists (the prices never rise).
Correctness
Suppose the optimal transaction buys on day b and sells on day s with b < s, yielding profit prices[s] - prices[b].
When the loop reaches day s, the variable min_price will hold min(prices[0..s-1]). Since the optimal buy day b is before s, we know prices[b] >= min_price. Therefore, prices[s] - min_price >= prices[s] - prices[b], and the algorithm will record at least the optimal profit (or better, if a cheaper buy day exists).
The algorithm never produces an invalid profit because every recorded value comes from price - min_price where min_price was set on an earlier iteration (or the same iteration, giving a difference of 0).
Complexity
- Time: O(n). We make a single pass through the array with constant work per element.
- Space: O(1). Only two variables are used regardless of input size.
Edge Cases
| Scenario | Behavior |
|---|---|
Single element [5] | Loop body executes once, sets min_price = 5, returns 0 |
Strictly decreasing [9, 7, 4, 1] | Every day updates min_price; profit never computed; returns 0 |
Strictly increasing [1, 3, 5, 8] | min_price stays at 1; profit grows each day; returns 8 - 1 = 7 |
All identical [4, 4, 4] | Profit always computes as 4 - 4 = 0; returns 0 |
Peak before valley [10, 15, 2, 8] | Best profit of 15 - 10 = 5 is recorded before min_price updates to 2 |
The last case is critical: a naive approach of max(prices) - min(prices) fails because it ignores the ordering constraint.
Solution
def single_transaction_profit(prices: list[int]) -> int:
min_price = float('inf') # lowest price seen so far
best_profit = 0 # best gain found; 0 means no transaction
for price in prices:
if price < min_price:
# New minimum price—update best buy candidate
min_price = price
else:
# Consider selling today at current price
best_profit = max(best_profit, price - min_price)
return best_profit
Trace for [7, 1, 5, 3, 6, 4]:
| Day | Price | min_price | best_profit |
|---|---|---|---|
| 0 | 7 | 7 | 0 |
| 1 | 1 | 1 | 0 |
| 2 | 5 | 1 | 4 |
| 3 | 3 | 1 | 4 |
| 4 | 6 | 1 | 5 |
| 5 | 4 | 1 | 5 |
The maximum profit is 5 (buy at 1, sell at 6).