Best Profit from a Capped Number of Round-Trip Trades
Dynamic ProgrammingAuto-graded · 25 test casesLast updated
Maximize profit from daily share prices using at most k non-overlapping buy-then-sell trades, testing state-based dynamic programming and handling a trade limit that never binds.
You are given the daily price of a single stock as a list, where the entry at index i is the price on day i. You are also given a cap on the number of round trips you may make.
A round trip consists of buying one share on some day and selling that same share on a later day (or the same day, which earns nothing). Your goal is to choose trades that maximize total profit.
Implement max_profit_capped_trades(max_trades, prices) which returns the largest total profit achievable using at most max_trades round trips.
Rules
- You may own at most one share at any moment. A share must be sold before another is bought.
- A sale and the next purchase may take place on the same day.
- You may make any number of round trips from zero up to
max_trades. If no trade yields a gain, the answer is0. - If
max_tradesis larger than the number of useful trades available, the unused allowance is simply ignored.
Input
max_trades: an integer, the maximum number of round trips allowed.prices: a list of integers, the stock price on each day in order.
Output
An integer: the maximum total profit.
Constraints
1 <= max_trades <= 1001 <= len(prices) <= 10000 <= prices[i] <= 1000
Examples
Example 1
Input: max_profit_capped_trades(2, [3, 8, 2, 6, 1, 9])
Output: 13
Example 2
Input: max_profit_capped_trades(3, [3, 8, 2, 6, 1, 9])
Output: 17
Example 3
Input: max_profit_capped_trades(1, [4, 2, 7, 1, 3])
Output: 5
Hints
Hint 1
Think of the problem as a small state machine: on each day you are either holding a share or not, and you also care how many trades you have started or completed so far.
Hint 2
For each trade index j, keep the best cash balance while holding the j-th share, and the best cash balance after completing j sales. Each day updates these using the previous trade's completed balance and the current price.
Hint 3
If max_trades is at least half the number of days, the cap can never matter, since each profitable trade needs its own rising step separated from the next. Then the answer is just the sum of all positive day-to-day increases.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model each day as a state machine. For every trade index j from 1 to max_trades, maintain two values:
hold[j]: the best cash balance while currently holding the share bought for tradej.done[j]: the best cash balance after fully completingjtrades (no share held).done[0]is fixed at0.
For each price p, and for j in increasing order:
hold[j] = max(hold[j], done[j-1] - p): keep the current position, or buy today after finishing tradej-1.done[j] = max(done[j], hold[j] + p): keep the current balance, or sell today to close tradej.
The answer is done[max_trades]. Because more allowed trades never hurt (an unused trade can be a zero-profit same-day buy and sell), this value already represents "at most" that many trades.
Shortcut. If 2 * max_trades >= n, the cap cannot bind. Every profitable trade needs at least one rising step, and two separate trades need a non-rising step between them, so there are at most about n/2 separate rising runs. In that case the answer is the sum of all positive day-to-day increases.
Why it is correct
The state (trades started or finished, holding or not) captures everything relevant to the future; the exact purchase day does not matter once its price is subtracted from the balance. Each transition corresponds to a legal action, and the max operations consider every legal sequence, so done[max_trades] is optimal.
Processing j in increasing order within a day lets hold[j] use the already updated done[j-1], which models selling and buying on the same day (allowed). Likewise done[j] uses the freshly updated hold[j]; buying and selling on the same day nets zero, so it cannot inflate the result.
For the shortcut, any trade from day a to day b earns the sum of daily changes in between, so the sum of positive changes is an upper bound. It is reached by trading each rising run separately, which is possible when the cap is large enough.
The sentinel -10**9 for hold means "not yet possible" and can never beat a real balance.
Complexity
- Time: O(n * max_trades) for the DP, O(n) for the shortcut.
- Space: O(max_trades), since each day depends only on the previous values.
Reference solution
from typing import List
def max_profit_capped_trades(max_trades: int, prices: List[int]) -> int:
n = len(prices)
if n < 2:
return 0
if 2 * max_trades >= n:
return sum(max(0, prices[i + 1] - prices[i]) for i in range(n - 1))
hold = [-10**9] * (max_trades + 1)
done = [0] * (max_trades + 1)
for p in prices:
for j in range(1, max_trades + 1):
cand_hold = done[j - 1] - p
if cand_hold > hold[j]:
hold[j] = cand_hold
cand_done = hold[j] + p
if cand_done > done[j]:
done[j] = cand_done
return done[max_trades]