Maximum Gain from Single Asset Trade
Arrays & HashingAuto-graded · 22 test casesLast updated
Determine the maximum possible gain achieved by completing at most one purchase and sale transaction over a sequence of prices.
Given an array of non-negative integers prices representing the value of an asset on successive days, determine the maximum profit achievable by buying on one day and selling on a subsequent day.
You may complete at most one buy and one sell transaction. You cannot sell an asset before buying it. If no positive profit can be made (for instance, if prices strictly decrease or remain constant), return 0.
Constraints
1 <= len(prices) <= 100,0000 <= prices[i] <= 1,000,000,000- Time complexity must be $O(n)$ where $n$ is the number of elements in
prices. - Auxiliary space complexity must be $O(1)$.
Examples
Example 1
Input: max_profit([7, 1, 5, 3, 6, 4])
Output: 5
Example 2
Input: max_profit([7, 6, 4, 3, 1])
Output: 0
Hints
Hint 1
To maximize profit when selling on day j, which earlier day should you select as the buying day?
Hint 2
Try maintaining the smallest price seen so far as you iterate through the sequence.
Hint 3
Can you update the overall maximum profit encountered at each step using only $O(1)$ additional storage?
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To maximize profit from a single trade, we need to choose a buying day $i$ and a selling day $j$ such that $i < j$ and $prices[j] - prices[i]$ is maximized.
Instead of testing all $O(n^2)$ pairs of buying and selling days, observe that for any fixed selling day $j$, the optimal day to buy is the day with the absolute lowest price among all days prior to $j$.
We can solve this in a single linear scan from left to right while keeping track of two scalar values:
min_price: the lowest price observed up to the day before the current day.best_profit: the maximum profit found so far (initialized to 0).
For each price in the array:
- Calculate the profit if we were to sell today:
price - min_price. - Update
best_profitif this calculated profit exceeds our current maximum. - Update
min_priceto include today's price as a potential future buying point.
Correctness
By tracking the minimum price seen strictly prior to the current day (or using an initial infinity value so selling on the first day yields negative infinity), we ensure that every prospective transaction respects the rule that buying must happen before selling. At every index $j$, best_profit stores the maximum of all valid trades ending on or before day $j$. Therefore, after visiting all elements, best_profit holds the global optimum or 0 if no positive profit was possible.
Complexity
- Time Complexity: $O(n)$, since we iterate through the array of $n$ prices once, performing constant-time operations at each step.
- Space Complexity: $O(1)$, because we only maintain a few scalar variables regardless of array length.
Python Reference Solution
from typing import List
def max_profit(prices: List[int]) -> int:
min_price = float('inf')
best_profit = 0
for price in prices:
best_profit = max(best_profit, price - min_price)
min_price = min(min_price, price)
return best_profit