Single Buy-Sell Transaction for Maximum Gain
Arrays & HashingAuto-graded · 18 test casesLast updated
Tests optimal single-pass tracking of minimum buy price to maximize profit from one stock transaction.
You receive a sequence of stock prices over consecutive days. Your task is to determine the largest gain possible from buying on one day and selling on a strictly later day. If no profitable transaction exists, report zero.
Write a function that accepts a list of daily prices and returns the maximum achievable profit.
Constraints
1 <= len(prices) <= 10^50 <= prices[i] <= 10^4- You must buy before you sell (the buy day index must be strictly less than the sell day index)
- You may complete at most one transaction (one buy followed by one sell)
- If no profit is possible, return
0
Examples
Example 1
Input: calculate_max_gain([7, 1, 5, 3, 6, 4])
Output: 5
Example 2
Input: calculate_max_gain([7, 6, 4, 3, 1])
Output: 0
Hints
Hint 1
Think about what information you need to track as you scan through the prices from left to right.
Hint 2
For each potential sell day, what was the best possible buy day before it?
Hint 3
You only need two variables: the lowest price seen so far and the best profit found so far.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The brute-force solution examines every buy-sell pair, checking all combinations where the buy index precedes the sell index. This requires O(n²) time, which becomes prohibitive for large inputs.
A more efficient strategy processes each price exactly once while maintaining two pieces of state: the lowest price encountered so far (representing the optimal historical buy point) and the maximum gain achieved up to the current moment.
When examining a potential sell price, the best corresponding buy price is always the minimum from all preceding days. By tracking this minimum incrementally, each day's optimal gain can be computed in constant time. The answer emerges as the maximum gain across all days.
Initialization starts with the first price as the tentative minimum and zero as the baseline gain (representing "make no trade"). For each subsequent price, compute what the gain would be by selling at that price against the tracked minimum, then update the maximum gain if this exceeds the previous best. Finally, update the minimum to include the current price, making it a candidate buy point for future days.
The order of operations matters: evaluate today's selling potential using yesterday's minimum, then incorporate today into the minimum. This ensures the buy strictly precedes the sell, preventing same-day transactions.
Why It Works
At each step, the algorithm considers every valid transaction that would sell on the current day. Since every transaction sells on some specific day, and we examine all days, the optimal transaction is guaranteed to be evaluated at its sell day. Tracking the running maximum across all days captures the global optimum.
The initialization to zero ensures that when prices only decline, the function correctly returns zero rather than a negative value.
Complexity
Time: O(n) — one pass through the array with constant work per element.
Space: O(1) — only two variables are maintained regardless of input size.
Solution
from typing import List
def calculate_max_gain(prices: List[int]) -> int:
lowest_so_far = prices[0]
max_gain = 0
for price in prices[1:]:
max_gain = max(max_gain, price - lowest_so_far)
lowest_so_far = min(lowest_so_far, price)
return max_gain