Problem 535994 · medium · Level 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 = [2, 6, 4, 11, 7, 12], fee = 3
Output: 8
Explanation: buy at 2, sell at 11 (profit 6 after fee); buy at 7, sell at 12 (profit 2 after fee).

Input:  prices = [4, 6, 9, 7, 13, 5], fee = 4
Output: 5
Explanation: one trade 4 -> 13 nets 5; 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…