Sneaker Resale With a Shipping Day

Harddynamic programmingAlso known as Best Time to Buy and Sell Stock with Cooldown

You resell one popular sneaker model from a small flat. There is room for only one pair at a time. A price tracker gives you a good forecast of the price for each of the next few days, and you can buy or sell at that day's price.

Every sale has to be packed and taken to the post office the next day, which eats the whole day. So on the day right after a sale you cannot buy. You can repeat buy-and-sell rounds as often as you like. How much can you make?

Your task

Write maxProfit(prices). prices[d] is the price on day d. Each day you do one thing: buy a pair (only if you hold none), sell your pair (only if you hold one), or wait. After a sale on day d, you may not buy on day d + 1.

Return the largest total profit (money from sales minus money spent on buying). Ending with a pair still unsold only loses money, so the best plan never does it. If no trade makes money, return 0.

maxProfit(prices: int[]) → int

Examples

Example 1
Input
prices = [4, 7, 2, 9, 1, 6]
Output
8
Why

Buy at 4, sell at 7 (+3). Day 2 is the shipping day. Wait on day 3. Buy at 1, sell at 6 (+5). Total 8. The biggest single jump, 2 to 9, earns 7, but selling on day 3 makes day 4 a shipping day, so you miss the 1 and end with 7.

Example 2
Input
prices = [3, 5, 2, 6]
Output
4
Why

Without the shipping day you could earn 2 + 4 = 6. But selling at 5 on day 1 blocks buying at 2 on day 2. The best is one trade: buy at 2, sell at 6.

Constraints

  • 0 ≤ prices.length ≤ 5,000
  • 0 ≤ prices[d] ≤ 1,000
Start with brute force

Try every plan: each day buy, sell or wait, where the rules allow. That is up to 3ⁿ plans; for 30 days it is already about 2 × 10¹⁴, and the limit is 5,000 days.

The well-known trick for unlimited trades, adding up every rise from one day to the next, ignores the shipping day. It gives 6 on the second example, where only 4 is possible.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code