Determine Highest Single Transaction Stock Profit
Arrays & HashingAuto-graded · 23 test casesLast updated
Find the maximum gain possible from buying and selling a stock once, given a sequence of daily values.
You are given an array of daily stock valuations prices, where prices[i] represents the valuation on day i.
Calculate the maximum possible profit achievable by selecting a single day to purchase the stock and a subsequent day to sell it.
If no positive profit can be made (for example, if stock values only decrease or remain constant), return 0.
Constraints
0 <= len(prices) <= 10^50 <= prices[i] <= 10^4
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
Example 3
Input: max_profit([1, 2])
Output: 1
Hints
Hint 1
Think about what price you would want to buy at if you decided to sell on day i.
Hint 2
As you iterate through the prices, keep track of the lowest price observed so far.
Hint 3
The potential profit on day i is simply prices[i] minus the minimum price seen prior to day i.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To maximize profit from a single transaction, we need to find a pair of days $(i, j)$ such that $i < j$ and $prices[j] - prices[i]$ is maximized.
A naive approach would evaluate all possible pairs of buy and sell days, which takes $O(n^2)$ time. However, we can optimize this to a single pass ($O(n)$ time):
- For any given sell day $j$, the optimal buy day $i$ (where $i < j$) is the day with the absolute minimum price seen prior to day $j$.
- We maintain a running variable,
lowest_price, to record the minimum price encountered so far. - At each step, we calculate the potential gain of selling on the current day (
price - lowest_price) and update our maximum profit (max_gain) if this gain is larger than any previous gain. - Afterwards, we update
lowest_priceto include the current day's price for future iterations.
If prices constantly drop or the input has fewer than two days, max_gain remains 0.
Complexity
- Time Complexity: $O(n)$, where $n$ is the length of
prices. We perform a single loop over the array with constant time operations per element. - Space Complexity: $O(1)$ auxiliary space, as we only maintain two scalar variables (
lowest_priceandmax_gain).
Python Reference Solution
from typing import List
def max_profit(prices: List[int]) -> int:
lowest_price = float("inf")
max_gain = 0
for price in prices:
max_gain = max(max_gain, price - lowest_price)
lowest_price = min(lowest_price, price)
return max_gain