Ad platform~25 min2s · 256 MBtarget O(n log k) time, O(k) spaceheaps
You work on an ad platform. A page has one ad slot, and the slot shows one ad in each tick of time. Each campaign has a number of ads to show. A campaign has a frequency cap: after its ad is shown, the campaign must rest for its own number of ticks before it can show again.
The platform always fills a tick with the ready campaign that has the most ads left, and the smaller campaign number on a tie. When no campaign is ready, the slot stays empty for that tick. Your team lead asks: "At which tick does each campaign show its last ad?" The campaigns hold up to 200,000 ads in all.
Write finish_ticks(counts, cooldowns).
counts[i] is the number of ads of campaign i, and cooldowns[i] is its rest. The total of counts is at most 200,000.i shows in tick t, it can show again from tick t + cooldowns[i] + 1.counts[i] is 0.Input: counts = [4, 2, 2], cooldowns = [2, 2, 1]
Output: [10, 5, 6]| Tick | Ready campaigns (ads left) | Shown |
|---|---|---|
| 1 | 0 (4), 1 (2), 2 (2) | 0 |
| 2 | 1 (2), 2 (2) | 1 |
| 3 | 2 (2) | 2 |
| 4 | 0 (3) | 0 |
| 5 | 1 (1), 2 (1) | 1: its last ad |
| 6 | 2 (1) | 2: its last ad |
| 7 | 0 (2) | 0 |
| 8, 9 | none | empty |
| 10 | 0 (1) | 0: its last ad |
Input: counts = [0, 3], cooldowns = [5, 0]
Output: [0, 3]A campaign with no ads has no last tick.
Input: counts = [2, 2, 2], cooldowns = [0, 0, 0]
Output: [4, 5, 6]With no rest, the campaigns rotate: 0, 1, 2, 0, 1, 2.
1 ≤ counts.length = cooldowns.length ≤ 100,000 (campaigns)0 ≤ counts[i] ≤ 200,000, and the total of counts is at most 200,0000 ≤ cooldowns[i] ≤ 10,000Going through the ticks one by one, and looking at every campaign in each tick, can mean billions of ticks. The schedule above has 2 empty ticks out of 10, but a schedule with large rests can be almost all empty.
Each ad needs one heap step to be chosen and one to rest. A rest costs one jump over the empty ticks. That is 200,000 ads × about 4 heap steps × 17 levels, about 14,000,000 steps.