Monitoring~30 min2s · 256 MBtarget O(n + h log n) time, O(n) spaceclassic twin: lc-2208greedy · heaps
A monitoring system watches the load of many servers, in requests a second. When the system is overloaded, an operator can halve the load of one server by moving traffic away. The load is a whole number, so halving rounds down: a load of 35 becomes 17.
Your team lead says: "Bring the total load down to half of what it was, with as few halvings as we can." A cluster can have 100,000 servers, and the same server can be halved again.
Write fewest_halvings(loads).
loads[i] is the load of server i. The starting total is the sum of all loads.x with x divided by 2, rounded down. The same server can be halved many times.Input: loads = [20, 9, 35, 6]
Output: 3The starting total is 70, so the goal is a total of 35 or less. Keep the loads in a max-heap, and halve the largest each time.
| Halving | Largest load | New load | Total after | Loads after |
|---|---|---|---|---|
| 1 | 35 | 17 | 52 | 20, 17, 9, 6 |
| 2 | 20 | 10 | 42 | 17, 10, 9, 6 |
| 3 | 17 | 8 | 33 | 10, 9, 8, 6 |
The total 33 is at most 35, so the answer is 3.
Input: loads = [1, 1, 1, 1]
Output: 2The total is 4, and the goal is 2 or less. Two halvings turn two loads into 0, and the total is 2.
Input: loads = [7]
Output: 1The total is 7. One halving gives 3, and twice 3 is 6, which is at most 7.
1 ≤ length of loads ≤ 10^5, and 1 ≤ loads[i] ≤ 10^7With 100,000 servers of 10^7, the answer can be 100,000 halvings. Scanning for the largest load before each halving costs 10^5 steps, so 10^10 steps in all.
A max-heap gives the largest load in one step and puts the halved load back in log n steps. The total reaches 10^12 and needs a 64-bit integer.