Ad platform~25 min2s · 256 MBtarget O(n) time, O(n) spacesliding-window-fixed · prefix-sums
An ad-serving system counts the impressions it serves in every hour of a long planning period. Engineers need to take the servers down twice for maintenance, and each outage lasts exactly k hours in a row.
The two outages must not overlap. The servers also need gap quiet hours between the end of the first outage and the start of the second, so that the caches warm up again.
Every impression served during an outage is lost, so you want to lose as few as possible. The planners ask for the smallest total number of impressions across both outages.
Write least_disrupted_total(load, k, gap).
load[i] is the number of impressions served in hour i.k consecutive hours. The first one starts at hour a, the second at hour b, and b ≥ a + k + gap.gap hours lie between them.2 * k + gap ≤ load.length, so at least one valid pair exists.Input: load = [7, 3, 9, 2, 6, 1, 8, 4, 5, 3], k = 2, gap = 1
Output: 15First compute the total of every window of 2 hours by sliding: totals = [10, 12, 11, 8, 7, 9, 12, 9, 8], where totals[s] covers hours s and s + 1. Then take each possible second start b in order. Its first outage may start at hour b - k - gap or earlier, so that start joins a running minimum.
| Second start b | Newest first start | Running minimum of first totals | Second total | Pair total | Best |
|---|---|---|---|---|---|
| 3 | 0 | 10 | 8 | 18 | 18 |
| 4 | 1 | 10 | 7 | 17 | 17 |
| 5 | 2 | 10 | 9 | 19 | 17 |
| 6 | 3 | 8 | 12 | 20 | 17 |
| 7 | 4 | 7 | 9 | 16 | 16 |
| 8 | 5 | 7 | 8 | 15 | 15 |
The best pair starts at hour 4 (hours 4 and 5: 6 + 1 = 7) and hour 8 (hours 8 and 9: 5 + 3 = 8). Hour 6 and hour 7 are not used, so at least gap hours lie between the outages.
Input: load = [0, 0, 0, 9, 9], k = 2, gap = 1
Output: 18The only valid pair is hours 0 and 1 with hours 3 and 4. Hour 2 is the gap. The windows at hours 0 and 2 would cost less, but they leave no gap.
Input: load = [4, 5, 6, 7], k = 1, gap = 0
Output: 9With one-hour outages and no gap, the two quietest hours are 4 and 5. They are neighbours, which is allowed when the gap is 0.
2 ≤ load.length ≤ 100,000 (hours in the planning period)0 ≤ load[i] ≤ 10^6 (impressions in one hour)1 ≤ k and 0 ≤ gap, with 2 * k + gap ≤ load.lengthTrying every pair of start hours costs about n^2 / 2 pairs, and adding up two windows for every pair multiplies that by k. With n = 100,000 and k = 20,000 that is far beyond what runs in two seconds.
A total can reach 2 × 100,000 × 10^6 = 2 × 10^11. That is beyond a 32-bit integer, so use a 64-bit type (long in Java, long long in C++).