FunctionRacerProblemsRace

Trading With Rest Days

MediumDynamic programmingPython, JavaScript, TypeScript, Java, C++

prices[i] is the price of one share on day i. You may buy and sell as often as you like, but you hold at most one share at a time and sell it on a later day than you bought it. Every sale costs fee. After selling on day d, you must rest: your next purchase can be on day d + rest + 1 at the earliest.

Return the largest total profit: what you sold for, minus what you paid, minus the fees. Doing nothing earns 0.

Example 1

prices [1,3,2,8,4,9]
fee 2
rest 0
returns 8

Buy at 1, sell at 8 (7 - 2 = 5), buy at 4 the next day and sell at 9 (5 - 2 = 3), for 8 in total.

Example 2

prices [1,3,2,8,4,9]
fee 2
rest 1
returns 6

Now buying on the day right after a sale is not allowed. Holding from the first day to the last earns 9 - 1 - 2 = 6.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Dynamic programming problems