Best Time to Buy and Sell Stock with Transaction Fee
Best Time to Buy and Sell Stock with Transaction Fee is LeetCode 714 (Medium). You get an array prices, where prices[i] is the price of one share on day i, and an integer fee. Return the maximum profit.
- You may trade as often as you like, but you can own at most one share at a time.
- Every completed trade, one buy plus its sell, costs
feeonce. - Never trading is allowed, so the answer is at least 0.
There are up to 5 × 10⁴ days, so the answer has to come from one pass over the prices.
- 1 <= prices.length <= 5 * 10⁴
- 1 <= prices[i] < 5 * 10⁴
- 0 <= fee < 5 * 10⁴
Intuition
Without a fee you would take every price rise. The fee changes the sums: two short trades pay it twice, while one long trade over the same days pays it once. Selling into a dip and buying back only pays when the dip is deeper than the fee.
Walk the days carrying two numbers:
- cash: the best profit so far while owning no share.
- hold: the best profit so far while owning one.
The fee sits on the sell move only: selling turns hold into hold + price − fee. A rise too small to pay the fee never lifts that above the cash you already have, so losing trades drop out with no extra check.
Unlimited trades plus a cost per trade is the signal. Track one best value per position (owning, not owning) and put the cost on exactly one of the moves between them.
Approach
Take [1, 3, 7, 5, 10, 3] with fee = 3. Compare one trade from 1 to 10 with two trades split at the dip to 5. Then think about which two numbers would let you make that choice day by day.
Start on day 0
Set cash = 0 and hold = -prices[0]. On the first day the only possible move is buying, and doing nothing leaves you with no profit and no share.
Cash: stay out, or sell and pay the fee
cash = max(cash, hold + price - fee). Either you already had no share, or you sell today's share and pay the fee. Charging the fee on this line means each completed trade pays it exactly once.
Hold: keep the share, or buy one
hold = max(hold, cash - price). Either you keep the share you own, or you buy at today's price out of cash. This reads the cash updated a moment ago, which is safe: selling and buying back on the same day just loses one fee, so it can never win.
Why this finds the best plan
Any legal sequence of trades moves back and forth between the two numbers, and each day's max keeps the best way of arriving at each. So the final cash is at least the profit of every plan, and since each value comes from a real plan, it is never more.
Return cash
The answer is cash after the last day. Ending in hold means a share was paid for and never sold, which only lowers the total.
Code in Python, C++ and Java
Common pitfalls
Charging the fee on the buy and the sell
cash = max(cash, hold + price - fee) hold = max(hold, cash - price - fee)
cash = max(cash, hold + price - fee) hold = max(hold, cash - price)
A trade is the buy and the sell together, and it pays one fee. Charging both halves doubles the cost: on [1, 3, 2, 8, 4, 9] with fee = 2 the answer drops from 8 to 4.
Taking each daily rise minus a fee
for i in range(1, len(prices)):
profit += max(0, prices[i] - prices[i - 1] - fee)cash = max(cash, hold + price - fee)
That charges a fee for every rising day, even when the days belong to one trade. On [1, 3, 7, 5, 10, 3] with fee = 3 it gives 3; buying at 1 and selling at 10 makes 6.
Selling as soon as a trade covers the fee
if price - buy > fee:
profit += price - buy - fee
buy = priceif price - buy > fee:
profit += price - buy - fee
buy = price - feeOn [1, 3, 7, 5, 10, 3] with fee = 3, selling at 7 and buying again at 5 pays the fee twice and makes 5, not 6. Resetting buy to price - fee lets a later, higher price extend the same trade instead.
Edge cases
[1, 4, 6] with fee = 10No sale ever lifts cash above 0, so the answer is 0 and no trade is made.
fee = 0The sell line loses its subtraction and the code sums every price rise, which is the right answer when trades are free.
Complexity
cash and hold once per day; no arrays.Best Time to Buy and Sell Stock with Transaction Fee FAQ
How is this different from the cooldown version, problem 309?
Both allow unlimited trades. The cooldown forbids buying the day after a sale, which needs a third state for that day. A fee only lowers what each sale earns, so two states and one subtraction are enough.
Does it matter whether the fee is paid when buying or when selling?
No, as long as it is paid once per trade. Moving it to the buy line, hold = max(hold, cash - price - fee), with no fee on the sell, gives the same answer.