Ctrl K

Profit With a Limited Number of Trades

Hard
You know the price of a coin for the coming days: rates[i] is its price on day i. A trade is buying the coin and selling it later. You can hold at most one coin at a time, so a new purchase is only possible after the previous coin is sold (the same day is fine). You may make at most max_trades trades. Return the largest total profit; if no profit is possible, return 0.
Example 1
max_trades=2, rates=[5, 1, 4, 2, 8, 3, 6] → 10

Buy at 1, sell at 8 (+7); buy at 3, sell at 6 (+3), 10 in total. Trading 1 → 4 and 2 → 8 instead would give only 9.

Example 2
max_trades=1, rates=[3, 7, 2, 6] → 4

The best single trade is 3 → 7 or 2 → 6, both earning 4.

Example 3
max_trades=4, rates=[10] → 0
Constraints
  • 1 ≤ max_trades ≤ 100
  • 1 ≤ len(rates) ≤ 1000
  • 0 ≤ rates[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWater Between Walls HardBiggest Solid Panel Block HardProfit From Two Trades HardEvery Way to Space the Words HardCrossing the Cave Hard
loading Python…
Input
max_trades=2, rates=[5, 1, 4, 2, 8, 3, 6]
Expected
10

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