Stock Trading With a Per-Sale Commission
Dynamic ProgrammingAuto-graded · 23 test casesLast updated
Compute the best total gain from repeatedly buying and selling a single share of a stock when each sale costs a flat commission, using a two-state dynamic program.
You are given a list prices, where prices[i] is the cost of one share of a stock on day i, and a non-negative integer fee, a flat commission paid every time you sell a share.
You may trade as often as you like, under these rules:
- You can own at most one share at any moment.
- To buy again, you must first sell the share you currently own.
- A buy and a sell each happen on a single day at that day's price. A day may include a sell followed by a buy.
- The commission
feeis paid once per completed trade (a buy followed by its sell). Buying costs nothing extra. - You are allowed to make no trades at all.
Return the largest total profit you can end up with, after all commissions are subtracted. A share bought but never sold does not count as a trade, and its purchase price is not recovered, so you should not end up with an unsold share if that lowers your profit.
If prices is empty, return 0.
Constraints
0 <= len(prices) <= 5 * 10^41 <= prices[i] <= 5 * 10^40 <= fee <= 5 * 10^4- The result is never negative, since doing nothing yields
0.
Examples
Example 1
Input: best_profit_after_commission([1, 3, 2, 8, 4, 9], 2)
Output: 8
Example 2
Input: best_profit_after_commission([1, 3, 7, 5, 10, 3], 3)
Output: 6
Example 3
Input: best_profit_after_commission([1, 2, 3, 4, 5], 0)
Output: 4
Example 4
Input: best_profit_after_commission([7, 6, 4, 3, 1], 2)
Output: 0
Hints
Hint 1
On any given day you are in one of two situations: you hold a share or you do not. Think about the best profit you could have achieved for each situation.
Hint 2
Write the transitions. Not holding after today means you either were already not holding, or you sold today and paid the fee. Holding after today means you either were already holding, or you bought today using yesterday's not-holding profit.
Hint 3
Summing every positive daily rise fails once a fee exists, because each small rise would pay its own fee. Start with not-holding = 0 and holding = -prices[0], update both each day, and return the not-holding value at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
At the end of each day you are in exactly one of two states:
free: the best profit achievable so far while holding no share.holding: the best profit achievable so far while holding one share (usually negative, since it includes the purchase price).
Each day, both states are updated from the previous day's values:
free = max(free, holding + price - fee): either stay out of the market, or sell today and pay the commission.holding = max(holding, previous_free - price): either keep the share you have, or buy today using the profit from the previous day's free state.
Initialize with free = 0 (no trades yet) and holding = -prices[0] (bought on day 0). The answer is the final free.
Why it is correct
By induction on the day: after day i, free is the best profit over all valid trade sequences on days 0..i that end with no share, and holding is the best over those ending with one share. The base case is day 0 by construction. For the step, any sequence ending with no share on day i either was already share-free on day i-1 or sold today from a holding state. Any sequence ending with a share either was already holding or bought today from a share-free state. Taking the maximum over those predecessors covers every possibility, and each predecessor is optimal by the inductive hypothesis.
Ending with an unsold share is never better than the free value, so returning free is right. The fee is charged at each sell, so each completed round trip pays it exactly once.
A simple greedy that adds up every daily rise fails here: with [1, 3, 2, 8] and fee = 2, it gets 4, while a single trade from 1 to 8 gets 5.
Complexity
- Time: O(n), one pass with constant work per day.
- Space: O(1).
Reference solution
from typing import List
def best_profit_after_commission(prices: List[int], fee: int) -> int:
if not prices:
return 0
free = 0 # best profit while holding no share
holding = -prices[0] # best profit while holding one share
for i in range(1, len(prices)):
price = prices[i]
prev_free = free
free = max(free, holding + price - fee)
holding = max(holding, prev_free - price)
return free