Calculate Maximum Single-Trade Return
Arrays & HashingAuto-graded · 19 test casesLast updated
Find the maximum non-negative profit from purchasing an asset on one day and selling it on a subsequent day.
You are given a list of integers prices, where prices[i] represents the price of a given asset on day i.
Determine the maximum profit achievable by completing at most one purchase and one sale of the asset. You must buy the asset on a given day before selling it on a later day. If no profitable trade can be executed, return 0.
Constraints
1 <= 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
Example 4
Input: max_profit([2, 1, 4, 1, 7])
Output: 6
Hints
Hint 1
If you choose to complete a trade on day j, what would be the optimal day i (where i < j) to purchase the asset?
Hint 2
Can you maintain the minimum price encountered so far as you iterate through the list from left to right?
Hint 3
Remember that you can execute zero transactions if prices continuously fall, so the baseline profit is always 0.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To solve this problem efficiently in a single pass ($O(N)$ time), we can leverage a key insight: if we decide to sell the asset on day $j$, our profit is maximized by purchasing the asset on the day prior to $j$ that offered the minimum historical price.
We can iterate through the list of daily prices while maintaining two variables:
min_price: The lowest asset price recorded up to the current day.max_gain: The maximum profit calculated so far across all valid buy/sell pairs.
For each element price in prices:
- Calculate potential profit if we sell today:
price - min_price. - Update
max_gainif this current trade yields a higher return than previously observed. - Update
min_priceif today's asset price is lower than our running minimum.
Since zero transactions are permitted, we initialize max_gain to 0. If prices decrease monotonically, max_gain remains 0.
Complexity Analysis
- Time Complexity: $O(N)$, where $N$ is the length of the
pricesarray. We iterate through the list once, performing constant-time arithmetic operations at each step. - Space Complexity: $O(1)$ auxiliary space, as only scalar variables are used to track state.
Python Source Code
from typing import List
def max_profit(prices: List[int]) -> int:
if not prices:
return 0
min_price = prices[0]
max_gain = 0
for price in prices[1:]:
max_gain = max(max_gain, price - min_price)
min_price = min(min_price, price)
return max_gain