Max Gains from Single and Multi-Trade Asset Strategies
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Calculate maximum achievable gain for an asset sequence under single-trade and unlimited-trade restrictions.
Given a list of positive integers representing the sequential daily values of an asset, calculate the maximum possible returns for two different trading strategies:
- Single Trade Strategy: You may complete at most one transaction (buy once and sell once on a later day).
- Unlimited Trades Strategy: You may complete as many non-overlapping transactions as you like (you can buy and sell multiple times, but you can hold at most one unit of the asset at any point, and a sale must take place after its corresponding buy).
If a strategy cannot yield any positive profit (for instance, if prices strictly decrease or remain flat), the return for that strategy should be 0.
Return a list of two integers: [max_single_trade_gain, max_unlimited_trades_gain].
Constraints
1 <= len(prices) <= 200,0001 <= prices[i] <= 2^31 - 1- Processing must run in $O(N)$ time.
Examples
Example 1
Input: compute_stock_profit([7, 1, 5, 3, 6, 4])
Output: [5, 7]
Hints
Hint 1
For a single trade, if you sell on day j, what is the best day i < j to buy?
Hint 2
For unlimited trades, notice that selling at peak B and buying at valley A yields the same gain as accumulating every single daily positive price rise between A and B.
Hint 3
You can compute both metrics concurrently in a single pass through the prices array.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can compute both strategies in a single $O(N)$ iteration over the price array.
-
Single Trade Strategy (One Buy, One Sell):
- At any day $j$, the optimal day to have bought the asset is the day with the lowest price up to day $j-1$.
- Maintain a running variable
min_pricetracking the smallest value observed so far. - For each day, check if selling at the current price yields a gain greater than our recorded best single-trade gain. Then, update
min_price.
-
Unlimited Trades Strategy (Multiple Buy-Sell Operations):
- Suppose the asset value goes up across consecutive days $i-1$ and $i$. The difference
prices[i] - prices[i-1]represents a positive gain. - A multi-day surge from price $A$ to price $B$ through intermediate prices is mathematically equal to the sum of all consecutive day-to-day positive increases within that interval: $$(P_2 - P_1) + (P_3 - P_2) + \dots + (P_k - P_{k-1}) = P_k - P_1$$
- Thus, greedily capturing every single positive adjacent difference
prices[i] - prices[i-1]guarantees the maximum potential sum across unlimited non-overlapping transactions.
- Suppose the asset value goes up across consecutive days $i-1$ and $i$. The difference
Complexity
- Time Complexity: $\mathcal{O}(N)$, as we visit each price entry exactly once.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space beyond the input list.
Python Reference Solution
from typing import List
def compute_stock_profit(prices: List[int]) -> List[int]:
if not prices:
return [0, 0]
min_price = prices[0]
single_trade_profit = 0
unlimited_trades_profit = 0
for i in range(1, len(prices)):
current_price = prices[i]
# Single trade strategy update
single_trade_profit = max(single_trade_profit, current_price - min_price)
min_price = min(min_price, current_price)
# Unlimited trades strategy update
daily_diff = current_price - prices[i - 1]
if daily_diff > 0:
unlimited_trades_profit += daily_diff
return [single_trade_profit, unlimited_trades_profit]