Ad platform~40 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1425monotonic-deque
A feed has a row of ad slots. Each slot has a score in units: a slot with a poor match has a negative score. An ad plan picks some slots, at least one, and adds up their scores.
To keep the page steady, two picked slots that follow each other in the plan can be at most gap positions apart. A feed can have 200,000 slots and gap can be 100,000, so looking back over the whole gap for every slot is too slow.
Write best_total_of_picks(scores, gap).
scores[i] is the score of slot i. It can be negative or zero.gap positions apart: if slots i and j follow each other, then j - i is at most gap.int, so return a 64-bit number.Input: scores = [4, -3, 6, -8, 5], gap = 2
Output: 15Let best[i] be the highest total of a plan that ends at slot i. A plan can start at slot i, or extend the best plan that ends within gap slots before it. Extend only when that plan's total is above 0. The queue of slots keeps those totals falling from the front to the back.
| Slot | Score | Best total | Queue after adding it |
|---|---|---|---|
| 0 | 4 | 4 | 0 |
| 1 | -3 | 1 (4 - 3) | 0, 1 |
| 2 | 6 | 10 (6 + 4) | 2 |
| 3 | -8 | 2 (-8 + 10) | 2, 3 |
| 4 | 5 | 15 (5 + 10) | 4 |
The plan with slots 0, 2 and 4 scores 4 + 6 + 5 = 15.
Input: scores = [-4, -9, -2], gap = 1
Output: -2Every slot is bad. The plan must have at least one slot, so the best plan is the single slot with score -2.
Input: scores = [5, -1, -1, -1, 5], gap = 2
Output: 9Slots 0 and 4 are 4 apart, so they cannot be neighbours in a plan. The plan with slots 0, 2 and 4 has neighbours 2 apart, and scores 5 - 1 + 5 = 9.
1 ≤ length of scores ≤ 2 × 10^5, and -10^6 ≤ scores[i] ≤ 10^61 ≤ gap ≤ 2 × 10^5Looking back over up to gap earlier slots at each slot costs close to n × gap steps. For n = 200,000 and gap = 100,000, that is about 1.5 × 10^10 steps.
A total can reach 2 × 10^11, which is far above a 32-bit int. The best earlier total in a sliding window is the front of a monotonic deque, so the pass costs O(n).