#714

Best Time to Buy and Sell Stock with Transaction Fee

Medium State machine DP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Trade as often as you like (one share at a time), paying a fee on every sale. Maximise profit.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: unlimited trades with a fee per sale.

Why this works: two states: holding a share or holding cash; pay the fee when selling.

Example: [1, 3, 2, 8, 4, 9], fee 2

buy 1 sell 8 (+5), buy 4 sell 9 (+3) → 8

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Charging the fee on both buy and sell.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon