← DiffPush

Best Time to Buy and Sell Stock with Transaction Fee

Standard Bar Dynamic Programming · DP on Stocks O(n) · O(1)

The Commission-Loaded Exchange

The broker's exchange now levies a flat commission on every completed cycle, regardless of its size. Trades stay unlimited, but each lock-release pair pays the toll once. Dispatch must skip marginal swings whose spread cannot clear the commission and focus on cycles that genuinely pay.

Input: An array prices where prices[i] is the fee on hour i, and an integer fee charged per completed transaction.

Output: Return the maximum total profit with unlimited transactions after paying fee once per buy-sell pair.

Constraints

Examples

Example 1

Input: {"prices":[1,3,2,8,4,9],"fee":2}
Output: 8
(8 - 1 - 2) + (9 - 4 - 2) = 5 + 3 = 8 across two cycles.

Example 2

Input: {"prices":[1,3,7,5,10,3],"fee":3}
Output: 6
One cycle from 1 to 10 nets 10 - 1 - 3 = 6.

Solve this in your browser →

Also on LeetCode ↗