Music streaming app~40 min2s · 256 MBtarget O(n) time, O(n) spacemonotonic-deque · dp
You work on a streaming app. A video has n slots where an ad break could start, and each slot has an attention score: how many viewers are expected to stay. The first slot always has a break, and so does the last.
Two breaks must not be too close or too far apart. Your team lead asks: "Where should the breaks go to collect the largest total attention?" There are up to 100,000 slots, and the gap rules can allow up to 100,000 slots between breaks.
Write best_break_plan(scores, low, high).
scores[i] is the attention score of slot i. Slots are numbered from 0.n - 1. Two neighbouring breaks are d slots apart, with low ≤ d ≤ high.-1 when no plan exists. When n = 1, the plan is the single slot 0.Input: scores = [4, 1, 6, 2, 9, 3, 5], low = 2, high = 3
Output: 24The best plan is the slots 0, 2, 4 and 6, with every gap equal to 2: 4 + 6 + 9 + 5 = 24.
Slot i |
Slots that can come before it (i - 3 to i - 2) |
Best total for slot i |
|---|---|---|
| 0 | the start | 4 |
| 1 | none | not reachable |
| 2 | 0 | 4 + 6 = 10 |
| 3 | 0 | 4 + 2 = 6 |
| 4 | 2 (slot 1 is not reachable) | 10 + 9 = 19 |
| 5 | 2 and 3 | max(10, 6) + 3 = 13 |
| 6 | 3 and 4 | max(6, 19) + 5 = 24 |
Input: scores = [8], low = 1, high = 1
Output: 8The first slot is also the last, so the plan is one slot.
Input: scores = [1, 100, 1], low = 2, high = 2
Output: 2The gap must be exactly 2, so the plan is slots 0 and 2. Slot 1 can never hold a break.
1 ≤ len(scores) ≤ 100,0000 ≤ scores[i] ≤ 1,000,0001 ≤ low ≤ high ≤ 100,000For each slot, looking at every possible previous break costs up to high - low + 1 steps. With a wide window that is up to 100,000 steps for each of 100,000 slots, which is 10 billion steps. You need about one step for each slot. A window that slides along the slots, and keeps its best candidate at the front, gives that.