PPractick

DSA interview question

Best Time to Buy and Sell Stock with Transaction Fee

Medium · Algorithms · Topics: dynamic programming, array, state machine

The problem

You're building a trading bot backend for a fintech app. The brokerage charges a flat fee on every completed transaction (buy + sell pair). You're given an array prices where prices[i] is the stock price on day i, and an integer fee representing the transaction fee. You can buy and sell as many times as you want, but you must sell before you buy again (i.e., you can only hold at most one share at a time). Your job: return the maximum profit achievable, accounting for the fee on every transaction.

Function signature

int maxProfit(vector<int>& prices, int fee);

Test cases

Input pricesfeeOutputExplanation
[1,3,2,8,4,9]28Buy@1, sell@8 (profit 7-2=5), buy@4, sell@9 (profit 5-2=3) → total 8
[1,3,7,5,10,3]36Buy@1, sell@10 (profit 9-3=6), skip other trades since fee eats profit
[1,2,3,4,5]13Buy@1, sell@5 (profit 4-1=3); splitting into multiple trades costs more fee
[1]20Can't complete any transaction
[]10Empty array
[5,4,3,2,1]10Prices only decrease — no profitable trade possible

(Always verify: does one big trade beat multiple small trades once fee is introduced? That's the crux of this problem.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the fee charged once per completed transaction (buy+sell pair), or separately on buy and on sell?
  2. Can I hold at most one share at a time (no multiple concurrent holdings)?
  3. Must I sell before buying again, or can I buy multiple times before selling?
  4. What's the range/size of prices and fee? (Signals whether O(n) is required vs O(n²) DP is acceptable.)
  5. Are prices guaranteed non-negative integers?

Follow-ups to expect

  1. "Can you do this in O(1) space?"
  2. "What if there's a limit on the number of transactions (like at most k trades)?"
  3. "What if there's a cooldown period after selling?"
  4. "Why does a greedy 'buy low, sell high on every uptick' approach fail here?"
  5. "Can you also return the actual days to buy/sell, not just profit?"
  6. "What if fee applies to both buy and sell separately?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in