Skip to content
Problem 714 · LeetCode 714(opens in a new tab)

Best Time to Buy and Sell Stock with Transaction Fee

MediumArrays

You are given prices, where prices[i] is what one share of a stock costs on day i, and a number fee. You may buy and sell as many times as you like, but you can own at most one share at a time, so each purchase must be sold before the next one.

Every completed trade, one buy plus its sale, costs fee once. Return the largest total profit you can end with. Not trading at all is allowed and earns 0.

Example 1

Input:  prices = [3, 7, 2, 9, 5, 8], fee = 2
Output: 8
Why:    trade 3→7, 2→9 and 5→8: (4 − 2) + (7 − 2) + (3 − 2)
2 more examples and the constraints

Example 2

Input:  prices = [4, 3, 2, 1], fee = 0
Output: 0
Why:    the price only falls, so never buy

Example 3

Input:  prices = [1, 3, 5], fee = 2
Output: 2
Why:    one trade 1→5 pays the fee once

Constraints

  • 1 ≤ prices.length ≤ 50,000
  • 1 ≤ prices[i] < 50,000
  • 0 ≤ fee < 50,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Two rows of DPO(n)
  2. Two running valuesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 daysVerdict
Two rows of DPO(n)
Passes; uses O(n) memory
Two running valuesO(n)
Best; same idea, O(1) memory

n = number of days. Both do one update per day.

Edge cases to test

  • One day. Nothing can be sold, so the answer is 0.
  • Falling prices. [4, 3, 2, 1] never rises, so do not trade: 0.
  • Fee larger than every rise. [2, 4, 3] with fee 5: no trade pays, so 0.
  • Fee of 0. The problem becomes the plain one: add up every rise.

Common mistakes

  • Charging the fee on both the buy and the sale, so each trade pays it twice.
  • Taking every price rise greedily, which pays the fee too many times.
  • Returning max(cash, hold): ending with an unsold share only lowers the profit.

How to talk through it

  1. 1Clarify. Is the fee charged once per buy and sell pair? Can I hold more than one share?
  2. 2Name the states. At the end of a day you either hold a share or you do not; keep the best profit for each.
  3. 3Give the moves. Selling goes from hold to cash at price minus fee; buying goes from cash to hold at minus price.
  4. 4Shrink the memory. Each day reads only the day before, so two variables are enough.
  5. 5Test out loud. Run one day, falling prices and a fee bigger than any rise.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?