Best Time to Buy and Sell Stock with Transaction Fee
LeetCode 714 · Medium · solution, intuition & step-by-step walkthrough
Subtract the fee once per transaction, on the sell edge.
This is how I solved Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714), a medium problem from the State Machine / Stocks pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Same two-mode state machine as the other stock problems — free to buy, or holding. The only twist is that every completed trade costs a fee, so charge it at the moment you sell.
Approach
- 1
State: (index, can_buy) → best profit from this day onward.
- 2
Buy mode: max(buy today, wait).
- 3
Hold mode: max(sell today − fee, wait).
- 4
Memoise with lru_cache; the answer is dfs(0, True).
How I solved it
State machine + memoPythonO(n) time · O(n) space
#2n > n, SC - 2n>n
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n = len(prices)
@lru_cache(maxsize=None)
def dfs(index,can_buy):
if index>=n:
return 0
if can_buy:
buy = -prices[index]+dfs(index+1,False)
hold= dfs(index+1,True)
return max(buy,hold)
else:
sell = prices[index]+dfs(index+1,True)-fee
hold= dfs(index+1,False)
return max(sell,hold)
return dfs(0,True)Best Time to Buy and Sell Stock with Transaction Fee — FAQ
What is the intuition behind Best Time to Buy and Sell Stock with Transaction Fee?
Same two-mode state machine as the other stock problems — free to buy, or holding. The only twist is that every completed trade costs a fee, so charge it at the moment you sell.
How do you solve Best Time to Buy and Sell Stock with Transaction Fee (LeetCode 714)?
1. State: (index, can_buy) → best profit from this day onward. 2. Buy mode: max(buy today, wait). 3. Hold mode: max(sell today − fee, wait). 4. Memoise with lru_cache; the answer is dfs(0, True).
What is the time and space complexity of Best Time to Buy and Sell Stock with Transaction Fee?
Time: O(n). Space: O(n). (Accepted approach: State machine + memo.)
What are common mistakes in Best Time to Buy and Sell Stock with Transaction Fee?
Charging the fee on both buy and sell double-counts it. Recursion depth grows with n — iterative two-variable DP avoids that for very long inputs.