LeetCode #714 Medium

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 fee once.
  • 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.

Constraints
  • 1 <= prices.length <= 5 * 10⁴
  • 1 <= prices[i] < 5 * 10⁴
  • 0 <= fee < 5 * 10⁴
dynamic-programmingarraygreedystate-machine
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maxProfit(self, prices: List[int], fee: int) -> int:
▶3 cash, hold = 0, -prices[0]
▶4 for price in prices[1:]:
▶5 cash = max(cash, hold + price - fee)
▶6 hold = max(hold, cash - price)
▶7 return cash
pricecashholdfee 21day 00−13day 12day 28day 34day 49day 5day 0: no share → 0, or buy at 1 → −1
cash0
hold−1
fee2
Two rows. Each column is a day. The cash row is the best profit while owning nothing, the hold row the best while owning one share. On day 0 you can only buy (−1) or do nothing (0).
pricecashholdfee 21day 00−13day 102day 28day 34day 49day 5selling nets 0, keep cash 0
day1price 3
sell0hold −1 + 3 − 2
cash0
Selling now would leave 0 after the fee, which does not beat 0. The price rose, but not by enough to pay the fee.
pricecashholdfee 21day 00−13day 10−12day 28day 34day 49day 5buying gives −3, keep hold −1
buy−3cash 0 − 3
keep−1
hold−1
Keeping the share bought earlier (−1) beats buying at 3 (−3). The share already held was cheaper, so it will sell for more.
pricecashholdfee 21day 00−13day 10−12day 208day 34day 49day 5selling nets −1, keep cash 0
day2price 2
sell−1hold −1 + 2 − 2
cash0
Selling now would leave −1 after the fee, which does not beat 0. The price did not rise enough to make a sale pay.
pricecashholdfee 21day 00−13day 10−12day 20−18day 34day 49day 5buying gives −2, keep hold −1
buy−2cash 0 − 2
keep−1
hold−1
Keeping the share bought earlier (−1) beats buying at 2 (−2). The share already held was cheaper, so it will sell for more.
pricecashholdfee 21day 00−13day 10−12day 20−18day 354day 49day 5sell at 8, pay 2 → cash 5
day3price 8
sell5hold −1 + 8 − 2
cash5
Selling yesterday's share at 8 and paying the fee gives 5, more than the 0 already banked, so this sale is worth its fee.
pricecashholdfee 21day 00−13day 10−12day 20−18day 35−14day 49day 5buying gives −3, keep hold −1
buy−3cash 5 − 8
keep−1
hold−1
Keeping the share bought earlier (−1) beats buying at 8 (−3). The share already held was cheaper, so it will sell for more.
pricecashholdfee 21day 00−13day 10−12day 20−18day 35−14day 459day 5selling nets 1, keep cash 5
day4price 4
sell1hold −1 + 4 − 2
cash5
Selling now would leave 1 after the fee, which does not beat 5. The price did not rise enough to make a sale pay.
pricecashholdfee 21day 00−13day 10−12day 20−18day 35−14day 4519day 5buy at 4 → hold 1
buy1cash 5 − 4
keep−1
hold1
Buying at 4 out of today's cash (5) leaves 1, better than the share held before (−1). A cheaper share means a bigger profit when it is sold.
pricecashholdfee 21day 00−13day 10−12day 20−18day 35−14day 4519day 58sell at 9, pay 2 → cash 8
day5price 9
sell8hold 1 + 9 − 2
cash8
Selling yesterday's share at 9 and paying the fee gives 8, more than the 5 already banked, so this sale is worth its fee.
pricecashholdfee 21day 00−13day 10−12day 20−18day 35−14day 4519day 581buying gives −1, keep hold 1
buy−1cash 8 − 9
keep1
hold1
Keeping the share bought earlier (1) beats buying at 9 (−1). The share already held was cheaper, so it will sell for more.
pricecashholdfee 21day 00−13day 10−12day 20−18day 35−14day 4519day 581answer: 8
cash8last day
trades2
fees paid4
Answer 8. Following the moves back from the last cash cell gives 2 trades, 4 paid in fees. Buy days are blue in the price row, sell days green.
05

Common pitfalls

Charging the fee on the buy and the sell

✗ Wrong
cash = max(cash, hold + price - fee)
hold = max(hold, cash - price - fee)
✓ Right
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

✗ Wrong
for i in range(1, len(prices)):
    profit += max(0, prices[i] - prices[i - 1] - fee)
✓ Right
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

✗ Wrong
if price - buy > fee:
    profit += price - buy - fee
    buy = price
✓ Right
if price - buy > fee:
    profit += price - buy - fee
    buy = price - fee

On [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.

06

Edge cases

A fee larger than any rise, e.g. [1, 4, 6] with fee = 10

No sale ever lifts cash above 0, so the answer is 0 and no trade is made.

fee = 0

The sell line loses its subtraction and the code sums every price rise, which is the right answer when trades are free.

07

Complexity

Time
O(n)
Space
O(1)
A single loop over the prices, updating cash and hold once per day; no arrays.
08

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.