Monitoring~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-881greedy
A monitoring platform runs health-check jobs, and each job needs a known amount of memory. The platform has a fixed number of servers, and a server can run at most two jobs at once.
All servers have the same memory limit, and the memory of the jobs on a server must fit within it. Buying bigger servers costs more, so the team wants the smallest limit that still fits every job.
You find that smallest limit, or report that no limit works.
Write smallest_memory_limit(loads, servers).
loads[i] is the memory that job i needs.servers servers. Each runs at most two jobs, and the total memory of its jobs must be at most the limit. All servers share the same limit.-1 if the servers cannot hold all the jobs, even with a very large limit.Input: loads = [2,3,4,6,7,9], servers = 3
Output: 11The solution sorts the jobs. Six jobs on three servers means every server runs a pair. The best pairing puts the lightest job with the heaviest, the second lightest with the second heaviest, and so on.
| Pair | Jobs | Memory |
|---|---|---|
| 1 | 2 and 9 | 11 |
| 2 | 3 and 7 | 10 |
| 3 | 4 and 6 | 10 |
The largest pair needs 11, so the smallest limit is 11.
Input: loads = [2,3,4,6,7,9], servers = 4
Output: 9With four servers, two of them hold a pair and two hold a single job. The two heaviest jobs, 7 and 9, run alone. The four lightest are paired as 2 with 6 and 3 with 4. The largest need is 9, a single job.
Input: loads = [2,3,4,6,7,9], servers = 2
Output: -1Two servers hold at most 4 jobs, and there are 6, so no memory limit helps.
1 ≤ len(loads) ≤ 100,000 and 1 ≤ loads[i] ≤ 1,000,0001 ≤ servers ≤ 100,000Trying every way to pair the jobs costs more than any power of 100,000, and trying every limit up to 100,000,000,000 adds a factor on top. Sorting once costs about 1,700,000 steps, and the pairing is one pass.