Best Time to Buy and Sell Stock with Transaction Fee
MediumDynamic Programming1d dp
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
prices[i] is a stock's price on day i, and every completed transaction (a buy followed by a sell) costs a flat fee, charged once per round trip.
You may make any number of transactions but hold at most one share at a time. Return the maximum total profit after fees; return 0 if trading never helps.
Examples
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Buy 1 sell 8 (profit 5 after fee), buy 4 sell 9 (profit 3 after fee).
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6
Buy at 1 and sell at 10 once: 9 - 3 = 6.
Constraints
- 1 <= prices.length <= 5 * 10^4
- 1 <= prices[i] < 5 * 10^4
- 0 <= fee < 5 * 10^4
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.