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 with room for only one pair at a time. A price tracker forecasts each day's price, and you can buy or sell at that price.

Every sale must be packed and posted the next day, which eats the whole day, so you cannot buy the day after a sale. You may trade as many rounds 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 (sales minus purchases). Ending with an unsold pair only loses money, so the best plan never does. 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 and sell at 7 for a profit of 3. Day 2 is the shipping day, so you cannot buy then, and you wait through day 3. Then you buy at 1 and sell at 6 for a profit of 5, which makes 8 in total. 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: buy, sell or wait each day, where allowed. That is up to 3ⁿ plans, about 2 × 10¹⁴ for 30 days, and the limit is 5,000 days.

The usual unlimited-trades trick, adding up every day-to-day rise, 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