Monitoring~18 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting · greedy
You work on a monitoring tool for a fleet of servers. Each server reports one load reading. An engineer compares servers in pairs, and the gap in a pair is the difference of its two readings.
Your team lead asks: "If we compare exactly k pairs, and no server is in two pairs, what is the largest total gap we can see?" The fleet can have 100,000 servers.
Write best_spread(readings, k).
readings[i] is the load reading of server i.k pairs of servers. No server is in more than one pair, and 2 × k is at most the number of servers.k gaps.Input: readings = [7, 2, 9, 4, 5, 1], k = 2
Output: 13Sort the readings to [1, 2, 4, 5, 7, 9]. Pair the lowest with the highest, and the next lowest with the next highest.
| Pair (low, high) | Gap |
|---|---|
| (1, 9) | 8 |
| (2, 7) | 5 |
The gaps add up to 13.
Input: readings = [3, 3, 3, 3], k = 2
Output: 0All readings are equal, so every gap is 0.
Input: readings = [10, 1], k = 1
Output: 9Two servers and one pair: the gap is 9.
2 ≤ len(readings) ≤ 100,0000 ≤ readings[i] ≤ 1,000,000,0001 ≤ k ≤ 50,000, and 2 × k ≤ len(readings)Choosing which servers to pair means trying a huge number of pairings, far more than any computer can check. But a sort takes about 1.7 million steps. If the best pairs always use the lowest and the highest readings, one sort and two sums give the answer.