Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714): Solution and Explanation

Medium
Array
Dynamic Programming
Greedy

Given daily stock prices and a fee charged once per completed trade, find the largest total profit. You may trade any number of times but can hold only one share at a time.

Intuition

At the end of every day you are in exactly one of two situations: you own a share or you do not. Nothing else about the past matters for the future, only how much profit you have in each situation.

So keep two numbers. cash is the best profit so far while owning nothing, and hold is the best profit so far while owning one share (it is usually negative, because the purchase price was subtracted).

Each day, owning nothing comes from owning nothing yesterday or from selling today, and selling pays the fee. Owning a share comes from keeping yesterday's share or buying today. The fee stops the DP from chasing every small wiggle, because a swing smaller than the fee never beats doing nothing.

Approach: Two-state DP (cash and hold)

  1. Set cash = 0 and hold = -prices[0]: on day 0 you either skip or buy.
  2. For each later day with price p, update cash = max(cash, hold + p - fee): rest, or sell the share you hold and pay the fee.
  3. Then update hold = max(hold, cash - p): keep the share, or buy today from your cash.
  4. After the last day, return cash. Finishing with no share is never worse than finishing with one.

Step-by-step example

prices = [1,3,2,8,4,9], fee = 2
  1. Day 0: cash = 0, hold = -1 (buy at 1).
  2. Day 1 (3): selling gives -1 + 3 - 2 = 0, no better than 0. Buying gives 0 - 3 = -3, worse than -1. Day 2 (2) changes nothing either.
  3. Day 3 (8): selling gives -1 + 8 - 2 = 5, so cash = 5. Buying from that cash gives 5 - 8 = -3, worse than -1, so hold stays -1.
  4. Day 4 (4): selling would give 1, keep cash = 5. Buying gives 5 - 4 = 1, better than -1, so hold = 1.
  5. Day 5 (9): selling gives 1 + 9 - 2 = 8, so cash = 8. The answer is 8: buy 1, sell 8, buy 4, sell 9.

Code: Python, Java, C++

1class Solution:
2    def maxProfit(self, prices: List[int], fee: int) -> int:
3        cash, hold = 0, -prices[0]
4        for i in range(1, len(prices)):
5            cash = max(cash, hold + prices[i] - fee)
6            hold = max(hold, cash - prices[i])
7        return cash
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the prices with constant work per day.

Space

O(1)

Only the two numbers cash and hold are kept.

Other approaches

DP arrays (time O(n), space O(n))

Keep cash[i] and hold[i] for every day. It is the same recurrence written out in full, handy for tracing back which days you traded, at the cost of O(n) memory.

Greedy with an effective buy price (time O(n), space O(1))

Track the cheapest effective buy price. When the price rises above it plus the fee, take the profit and set the new buy price to price - fee, so a later higher sale can extend the trade without paying the fee again.

Common mistakes

  • Charging the fee on both the buy and the sell. It is paid once per trade, so put it on one side only.
  • Starting hold at 0. On day 0 holding a share means you paid for it, so hold starts at -prices[0].
  • Returning max(cash, hold). Holding an unsold share never adds profit, so the answer is cash.
  • Using the greedy from Stock II (sum every rise). With a fee, many small rises cost more in fees than one long trade.

Frequently asked questions

Is it a bug that hold uses the cash value updated on the same day?

No. Using the new cash would mean selling and buying on the same day, which only pays an extra fee, so it never wins. Both orders give the same answer.

Why is the answer cash and not hold?

hold counts the money spent on a share you still own. Selling it on the last day, or never buying it, is always at least as good, and cash already includes both options.

How is this different from Stock with Cooldown?

The cooldown version needs a third state for the day after a sale. Here the only extra cost is the fee, so two states are enough.

Can the fee make the best answer zero?

Yes. If no rise is larger than the fee, every trade loses money and the best plan is to never trade.