Ctrl K

Trades With a Commission

Medium
You know the price of a coin for the coming days: rates[i] is its price on day i. You may make as many buy-then-sell trades as you like, but you can hold at most one coin at a time. Every completed trade (a purchase together with its sale) costs a commission. Return the largest total profit after commissions.
Example 1
rates=[2, 8, 6, 10], commission=3 → 5

One trade 2 → 10 earns 8 − 3 = 5. Two trades 2 → 8 and 6 → 10 earn (6 − 3) + (4 − 3) = 4, since the second commission eats the gain. The answer is 5.

Example 2
rates=[1, 5, 2, 9], commission=1 → 9

Two trades pay off here: 1 → 5 and 2 → 9 give (4 − 1) + (7 − 1) = 9, while a single 1 → 9 gives only 7.

Example 3
rates=[5, 6], commission=2 → 0

The rise of 1 is smaller than the commission, so it is best not to trade: 0.

Constraints
  • 1 ≤ len(rates) ≤ 5·10⁴
  • 0 ≤ rates[i] < 5·10⁴
  • 0 ≤ commission < 5·10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumLongest Seesaw Subsequence MediumFewest Meetings to Cancel Medium
loading Python…
Input
rates=[2, 8, 6, 10], commission=3
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.