Best Time to Buy and Sell Stock with Transaction Fee solution explained

Best Time to Buy and Sell Stock with Transaction Fee is solved with a two-state DP: track the best profit if you end the day holding no share (cash) and if you end it holding one (hold). Each day, cash = max(cash, hold + price - fee) and hold = max(hold, cash - price). One pass, O(n) time and O(1) memory, and the answer is cash at the end.

By Published 8 min read

What you are asked to do

You get a list of daily prices for one stock and a fee that is charged once for every complete buy-then-sell. You may make as many round trips as you like, but you can hold at most one share, so you must sell before you buy again. Return the largest profit you can finish with after paying all fees. Doing nothing is allowed, so the answer is never negative.

Price series and fees invented for this page
PricesFeeBest profitWhy
[3, 8, 2, 9]28Two trades: 8 - 3 - 2 = 3, then 9 - 2 - 2 = 5
[2, 4, 3, 5, 4, 6]22Each small rise is eaten by the fee; one trade from 2 to 6 nets 2
[4, 6, 5, 9]32Buy at 4 and sell at 9; splitting into two trades pays the fee twice
[9, 7, 5, 3]10Prices only fall, so never trade
[1, 5, 3, 8, 4, 9]28Three trades of 2, 3 and 3 beat one long trade worth 6
Price series and fees invented for this page. Scroll sideways on a small screen.

Confirm the details first. Is the fee charged per trade or per share? Can you sell and buy again on the same day? Can the fee be zero? Can the list be empty? The standard version charges one fee per round trip, and selling then rebuying on the same day is never useful when the fee is positive.

Where it fits in an interview

This problem belongs to the stock-trading family, and interviewers like that family because one framework solves every member. Here the fee breaks the greedy shortcut that works when trades are free, so a candidate who memorized "add every rise" gets caught. The question tests whether you can name the states (holding a share or not), write the transitions, and then notice that only yesterday's values are needed. It is usually a medium-level question, sometimes followed by a variant with a cooldown day or a limit on trades.

Why the greedy shortcut breaks

Without a fee, the best profit is the sum of every day-to-day rise, because any long trade can be cut into daily pieces with the same total. With a fee, each piece costs the fee again. On [2, 4, 3, 5, 4, 6] with a fee of 2, every daily rise is exactly 2, so taking each one nets zero. Holding from 2 all the way to 6 rides through the dips and pays the fee once, for a profit of 2. The decision on each day depends on whether you already hold a share and what it cost you, which is exactly what a state machine records.

Slow approach: try every buy and sell pair

A direct search picks the next buy day and sell day, books that trade, and recurses on the days after the sale. It also considers stopping. Written as plain recursion it is exponential. With a cache on the start day it drops to O(n³), which is still far too slow for long price histories, but it is easy to trust and makes a good reference.

def fee_profit_slow(prices, fee, start=0):
    best = 0  # stop trading from here on
    for buy in range(start, len(prices)):
        for sell in range(buy + 1, len(prices)):
            gain = prices[sell] - prices[buy] - fee
            best = max(best, gain + fee_profit_slow(prices, fee, sell + 1))
    return best
Pair search: easy to trust, exponential without a cache.

Main approach: two states, rolled forward

At the end of any day you are in one of two situations. Define cash as the best profit so far while holding no share, and hold as the best profit so far while holding one (the purchase price has already been subtracted). Before the first day, cash is 0 and hold is impossible, which we write as minus infinity.

  • cash today = the larger of cash yesterday (do nothing) and hold yesterday + price - fee (sell today and pay the fee).
  • hold today = the larger of hold yesterday (keep the share) and cash yesterday - price (buy today).

Both updates read only yesterday's values, so two variables are enough. In Python a tuple assignment computes both right-hand sides before storing; in JavaScript use temporary variables. At the end, cash is the answer, since finishing with an unsold share can never beat having sold it or never bought it.

def max_profit(prices, fee):
    cash = 0              # best profit holding no share
    hold = float("-inf")  # best profit holding one share
    for p in prices:
        cash, hold = max(cash, hold + p - fee), max(hold, cash - p)
    return cash
Python: one pass, O(n) time, O(1) extra memory.
function maxProfit(prices, fee) {
  let cash = 0;
  let hold = -Infinity;
  for (const p of prices) {
    const nextCash = Math.max(cash, hold + p - fee);
    const nextHold = Math.max(hold, cash - p);
    cash = nextCash;
    hold = nextHold;
  }
  return cash;
}
JavaScript: the same two states with explicit temporaries.

Walk [3, 8, 2, 9] with a fee of 2. Day 1: cash 0, hold -3. Day 2: cash max(0, -3 + 8 - 2) = 3, hold max(-3, 0 - 8) = -3. Day 3: cash stays 3, hold max(-3, 3 - 2) = 1. Day 4: cash max(3, 1 + 9 - 2) = 8. The answer, 8, matches the two trades in the table.

Complexity

Comparison for n days
ApproachTimeMemoryVerdict
Pair search, no cacheExponentialO(n) stackReference only
Pair search, cached on start dayO(n³)O(n)Correct but slow for long histories
Two arrays, cash[i] and hold[i]O(n)O(n)Clear for explaining the states
Two rolling variablesO(n)O(1)The answer to give
Comparison for n days. Scroll sideways on a small screen.

Edge cases

  • Empty list or a single day: no trade can finish, so the answer is 0. The code above returns 0 without special handling.
  • Prices that only fall: cash never grows, and the answer stays 0.
  • Fee of zero: the method still works and reduces to summing every rise.
  • Fee larger than any possible gain: no trade is worth making, and the result is 0.
  • Flat stretches of equal prices: nothing changes in either state, which is correct.
  • Fixed-width integers: profit adds up across many trades, so cash can grow well past any single price; check your bounds. Also start hold at a safe negative value rather than the smallest integer, because adding a price to that can overflow.

Common slip-ups

  • Charging the fee on both the buy and the sell. That doubles it. Subtract it once per round trip, on either side.
  • Summing max(0, rise - fee) for each day. That pays a fee for every small step and misses long trades. [2, 4, 3, 5, 4, 6] with a fee of 2 returns 0 instead of 2.
  • Starting hold at 0. That pretends you got a share for free. Start it at minus infinity, or at -prices[0] after reading the first day.
  • Updating cash, then using the new cash for hold in JavaScript. It happens to give the same answer here, since selling and rebuying on one day only loses a fee, but say whether you meant it. In variants with a cooldown, the same habit is a real bug.
  • Returning max(cash, hold). hold includes a share you never sold, so it is never the right final answer.

An answer in the room

Fictional example

A candidate setting up the states
Candidate
Summing every rise is the free-trading answer, but here each trade pays the fee, so short trades can lose. I need to know whether I hold a share on each day.
Candidate
So two values: cash, the best profit with no share, and hold, the best with one share. Selling moves hold to cash and pays the fee; buying moves cash to hold.
Candidate
Each day only needs yesterday's pair, so it's linear time and constant space. On 3, 8, 2, 9 with fee 2 that ends with cash equal to 8.

Also in this set

Remove Boxes sits at the opposite end of difficulty, with three indexes and a quartic bound, and is worth seeing next to this two-variable solution. Minimum Score Triangulation of Polygon shows interval DP, the other big family of table-based problems. For a broader topic review, try algorithm interview questions.

Using Natively to practice

When you work through the stock-trading family, Natively can read a problem from a screenshot and propose states, transitions and code in its overlay, so you can check your cash and hold updates once you have written them yourself. During a mock interview it can transcribe the session on your computer, and the transcript shows whether you explained the fee and the greedy trap clearly. See an AI interview assistant for Mac and Windows.

Questions people ask

How do you solve Best Time to Buy and Sell Stock with Transaction Fee?

Keep two values while scanning the prices: cash, the best profit holding no share, and hold, the best profit holding one. Each day set cash = max(cash, hold + price - fee) and hold = max(hold, cash - price). Return cash.

What is the time and space complexity?

O(n) time for one pass over n prices and O(1) extra space, because each day only needs the previous day's two values.

Why doesn't adding every price increase work with a fee?

Each separate trade pays the fee, so many small trades can lose money where one longer trade would profit. On [2, 4, 3, 5, 4, 6] with a fee of 2, taking every rise nets 0 but one trade from 2 to 6 nets 2.

Should the fee be subtracted when buying or when selling?

Either, as long as it is charged exactly once per round trip. Subtracting it on the sell is the most common way to write it; charging it on both sides is a bug.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP