Ctrl K

Trades With a Rest Day

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. There is one rule: you cannot buy on the day right after a sale; that day is a rest day. Return the largest total profit you can make.
Example 1
rates=[3, 5, 0, 0, 4] → 6

Buy at 3 and sell at 5 (+2), rest the next day, then buy at 0 and sell at 4 (+4). That is 6 in total.

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

Selling at 4 would spend the day priced 2 on rest, leaving no room for a second trade. Holding to the end is better: 7 − 1 = 6.

Example 3
rates=[4] → 0

There is only one day, so no profit is possible.

Constraints
  • 1 ≤ len(rates) ≤ 5000
  • 0 ≤ rates[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
rates=[3, 5, 0, 0, 4]
Expected
6

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