Online store~35 min2s · 256 MBtarget O(n) time, O(n) spacedp · intervals
An online shop can run one promotion on any day of a campaign. Each day has an expected revenue for the promotion on that day. After a promotion, the shop must wait for a cooldown, so that customers do not get tired of offers. Big promotions need longer cooldowns.
The marketing team wants to pick the days to run promotions so that the total expected revenue is as large as possible.
Write max_revenue(revenue, cooldown).
i, the shop may run a promotion that earns revenue[i] units.i, the next promotion can run on day i + cooldown[i] + 1 or later. With cooldown[i] = 0, the next day is allowed.long.Input: revenue = [4, 9, 3, 7, 5, 2], cooldown = [1, 2, 0, 1, 0, 3]
Output: 16The trace works from the last day back. For each day, it compares skipping the day with running the promotion and resuming after its cooldown.
| Day | Revenue | Cooldown | Next day it may run | Skip it | Run it | Best from this day |
|---|---|---|---|---|---|---|
| 5 | 2 | 3 | 6 | 0 | 2 | 2 |
| 4 | 5 | 0 | 5 | 2 | 7 | 7 |
| 3 | 7 | 1 | 5 | 7 | 9 | 9 |
| 2 | 3 | 0 | 3 | 9 | 12 | 12 |
| 1 | 9 | 2 | 4 | 12 | 16 | 16 |
| 0 | 4 | 1 | 2 | 16 | 16 | 16 |
One best plan runs days 1, 4 and 5: 9 + 5 + 2 = 16. Another runs days 0, 2, 3 and 5: 4 + 3 + 7 + 2 = 16. No plan earns more, so the output is 16.
Input: revenue = [7], cooldown = [3]
Output: 7There is one day. Running the promotion earns 7, and the cooldown does not matter. The output is 7.
Input: revenue = [10, 6, 6], cooldown = [2, 0, 0]
Output: 12Day 0 earns 10, but its cooldown blocks days 1 and 2, which earn 6 each. Skipping day 0 and running days 1 and 2 earns 12, so the output is 12.
1 ≤ revenue.length ≤ 100,000; cooldown has the same length0 ≤ revenue[i] ≤ 10,000,000 (units)0 ≤ cooldown[i] ≤ 100,000 (days)Trying every set of days that respects the cooldowns takes time that grows exponentially, up to 2^n. The best plan from day i onward only depends on i, so there are only n different questions. Answering each with two choices costs about n steps. The total can reach 10^5 × 10^7 = 10^12, which needs a 64-bit integer.