Problem 535994 · medium · Phase 05 Advanced Algorithms & Graphs

Trades With Commission

dynamic programming · 1-D dp · state machine · stock trading

You watch one share's price for n days, prices[i] on day i. On any day you may buy one share (only if you hold none) or sell the share you hold; the broker charges a flat fee on every sale. You may make as many round trips as you like. Return the maximum total profit (0 if trading never helps).

Examples

Input:  prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: buy at 1, sell at 8 (profit 5 after fee); buy at 4, sell at 9 (profit 3 after fee).

Input:  prices = [1, 3, 7, 5, 10, 3], fee = 3
Output: 6
Explanation: one trade 1 -> 10 nets 6; two shorter trades would pay the fee twice.

Constraints

  • 0 <= len(prices) <= 10**5
  • 0 <= prices[i], fee <= 10**5
  • Target complexity: O(n) time.

Goals

  • Model holding and not-holding as two dp states
  • Charge a transaction fee exactly once per round trip
Starting Python…