Ctrl K

As Many Trades as You Like

Medium
You know the price of a coin for the coming days: rates[i] is its price on day i. Each day you may buy the coin, sell it, or do nothing, but you can hold at most one coin at a time. Selling and buying on the same day is allowed. There is no limit on the number of trades. Return the largest total profit you can make.
Example 1
rates=[5, 2, 6, 4, 9, 9] → 9

Buy at 2 and sell at 6 (+4), then buy at 4 and sell at 9 (+5). That is 9 in total.

Example 2
rates=[1, 3, 6, 10] → 9

The price only rises: buy on the first day and sell on the last, 10 − 1 = 9. Selling and rebuying along the way adds nothing.

Example 3
rates=[8, 8, 3] → 0

The price never goes up, so trading cannot help; the answer is 0.

Constraints
  • 1 ≤ len(rates) ≤ 3·10⁴
  • 0 ≤ rates[i] ≤ 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 MediumLongest Seesaw Subsequence MediumFewest Meetings to Cancel MediumLongest Chain of Segments Medium
loading Python…
Input
rates=[5, 2, 6, 4, 9, 9]
Expected
9

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