Stock Trading Profit with Transaction Limits and Fees
Dynamic ProgrammingModel answerLast updated
Maximize stock trading profit given a cap on total transactions and a per-sale fee, using a unified DP state machine.
Stock Trading Profit with Transaction Limits and Fees
You are building a profit calculator for a trading platform that enforces two constraints: a cap on how many trades a user can make, and a flat fee charged every time they sell.
Given a list of daily prices prices, an integer k (maximum number of buy/sell pairs allowed), and a number fee (cost deducted at the time of each sale), return the maximum total profit achievable.
def max_profit(prices: list[int], k: int, fee: float) -> float:
pass
Rules
- You may complete at most
ktransactions. One transaction = one buy followed by one sell. - You must sell your current share before buying again (no overlapping positions).
- The
feeis charged once per transaction, at the moment of sale. - Holding and doing nothing is always allowed — you are never forced to trade.
Constraints
1 <= len(prices) <= 10^40 <= prices[i] <= 10^50 <= k <= 10^90 <= fee <= 10^5
Examples
Example 1
prices = [1, 3, 2, 8, 4, 9], k = 2, fee = 2
Output: 8.0
Buy on day 0 (price 1), sell on day 3 (price 8): profit = 7 − 2 = 5.
Buy on day 4 (price 4), sell on day 5 (price 9): profit = 5 − 2 = 3.
Total = 8.0.
Example 2
prices = [1, 2], k = 1000000000, fee = 0
Output: 1.0
No fee, effectively unlimited trades; only one profitable move exists.
What is expected
- A correct implementation that handles all constraint ranges, including
kup to 10^9. - A brief explanation of your approach, why naive greedy fails when
fee > 0, and the time and space complexity of your solution.
Hints
Hint 1
At most ⌊n/2⌋ transactions can ever be profitable in n days (each needs a distinct buy day before its sell day). If k is larger than that, the cap never actually binds — treat it as unlimited trades and solve with two scalars instead of a huge array.
Hint 2
Model each day as a state machine with two states: 'free' (no stock held, tracks max cash after j completed sales) and 'holding' (own one share, tracks max cash while in the j-th open trade). The transitions are: open a position by subtracting today's price from the free state, close it by adding today's price and subtracting the fee.
Hint 3
Greedy 'sum every upswing' stops working the moment fee > 0, because merging two adjacent up-moves into one transaction saves a fee. The DP captures this automatically — you don't need to special-case it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why greedy fails with a fee
Without a fee, the answer is simply the sum of every positive day-over-day price increase. Once a fee is charged per sale, two adjacent rises may be cheaper to combine into one transaction than to sell and rebuy in the middle. A pure greedy sum over upswings overcounts fees and gives the wrong answer. Dynamic programming is needed to decide when merging transactions is worth it.
State machine
At any point you are in one of two states:
- Free: you hold no stock.
sell[j]is the maximum cash after completing exactlyjfull transactions. - Holding: you own one share.
buy[j]is the maximum cash currently in your pocket while thej-th transaction is open (you have already spent cash on the buy).
For each price p, the transitions are:
buy[j] = max(buy[j], sell[j-1] - p) # enter transaction j
sell[j] = max(sell[j], buy[j] + p - fee) # exit transaction j, pay fee
Iterating j from 1 to k each day, in forward order, gives the correct answer. In-place updates within a single day are safe: buying and selling the same share on the same day yields at most −fee ≤ 0, so it can never improve on simply doing nothing.
The answer is sell[k] because sell[j] is non-decreasing in j — you can always choose not to use an extra transaction slot.
Handling k up to 10^9
A profitable transaction requires a buy day strictly before its sell day, and positions cannot overlap. At most n // 2 such pairs fit in n days. When k >= n // 2, the transaction cap is irrelevant, so the full k-dimensional DP collapses to two scalars:
cash, hold = 0.0, float("-inf")
for p in prices:
cash = max(cash, hold + p - fee)
hold = max(hold, cash - p)
return float(cash)
This check must happen before any array allocation, or a k = 10^9 input will exhaust memory.
Complexity
| Case | Time | Space |
|---|---|---|
k >= n // 2 | O(n) | O(1) |
k < n // 2 | O(n · k) | O(k) |
| Overall | O(n · min(k, n/2)) | O(min(k, n/2)) |
In the worst case k ≈ n/2 = 5000 and n = 10^4, giving roughly 5 × 10^7 simple operations — well within limits.
Edge cases
k == 0or a single price: no transaction can complete, return0.0.- Strictly falling prices or a fee larger than every upswing: the DP naturally returns
0.0since no trade ever helps. feeis a float, so the return type should always befloat.k = 10^9must hit the shortcut before any list of that size is created.
Solution
def max_profit(prices: list[int], k: int, fee: float) -> float:
n = len(prices)
if n < 2 or k == 0:
return 0.0
# When k is large enough that the cap never binds, use O(1) space.
if k >= n // 2:
cash, hold = 0.0, float("-inf")
for p in prices:
cash = max(cash, hold + p - fee)
hold = max(hold, cash - p)
return float(cash)
# Finite k: track buy[j] and sell[j] for j = 1..k transactions.
buy = [float("-inf")] * (k + 1)
sell = [0.0] * (k + 1)
for p in prices:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - p)
sell[j] = max(sell[j], buy[j] + p - fee)
return float(sell[k])
Common mistakes
- Skipping the
k >= n // 2guard. This causes a memory error for largekand is the single most common failure on this problem. - Charging the fee on the buy instead of the sell. Either placement is consistent on its own, but mixing them produces a wrong answer.
- Using separate "today" and "yesterday" arrays. It is not necessary here (same-day round trips are never profitable), but candidates who convince themselves it is required and implement it incorrectly waste time and introduce bugs.
- Returning an
int. The fee is a float; always returnfloat(sell[k]).
Follow-up directions
Cooldown period. If a one-day cooldown is required after each sale, the buy transition on day i must draw from the free state of day i − 2 rather than day i − 1. Keep a prev_cash variable lagging one extra day; time complexity is unchanged.
O(1) space for finite k. The Lagrangian relaxation (Aliens trick) binary-searches a per-transaction penalty λ and runs the O(1)-space unlimited DP with fee + λ. This finds the λ at which the unconstrained optimum uses exactly k transactions, giving O(n log C) time and O(1) space regardless of k.
Short selling. Add a third state representing an open short position. Entering a short sells at today's price; covering it buys back at a later price minus the fee. Positions remain mutually exclusive and the transaction counter increments on close, keeping the same O(n · min(k, n/2)) complexity.