Payments app~30 min2s · 256 MBtarget O((s + m) log s) time, O(s) spaceclassic twin: lc-1882heaps
A payments app settles transactions with a pool of servers. Each server has a weight, which is its cost to run. Job j arrives at time j, and the jobs are handled in order.
Your team lead asks: "Give each job to the cheapest server that is free. If none is free, the job waits." You know the weight of each server and how long each job runs.
Write assign_servers(weights, durations).
0 to s - 1, and server i has weight weights[i]. Jobs are numbered 0 to m - 1. Job j arrives at time j and runs for durations[j] time units.t is free at time t.durations[j] time units.Input: weights = [5, 1, 3], durations = [4, 1, 2, 6, 2, 3, 1]
Output: [1, 2, 2, 0, 1, 2, 1]The table shows the time each job is handled, the free servers with their weights, the server chosen and the time it is free again.
| Job | Time handled | Free servers (weight) | Chosen | Busy until |
|---|---|---|---|---|
| 0 | 0 | 0 (5), 1 (1), 2 (3) | 1 | 4 |
| 1 | 1 | 0 (5), 2 (3) | 2 | 2 |
| 2 | 2 | 0 (5), 2 (3) | 2 | 4 |
| 3 | 3 | 0 (5) | 0 | 9 |
| 4 | 4 | 1 (1), 2 (3) | 1 | 6 |
| 5 | 5 | 2 (3) | 2 | 8 |
| 6 | 6 | 1 (1) | 1 | 7 |
Input: weights = [2, 9], durations = [5, 5, 5]
Output: [0, 1, 0]At time 2 both servers are busy. The first one frees at time 5, and job 2 waits until then.
Input: weights = [4, 4, 4], durations = [1, 1, 1, 1]
Output: [0, 0, 0, 0]Server 0 is free again at the time of each job, and it wins every tie.
1 ≤ length of weights ≤ 100,000 and 1 ≤ length of durations ≤ 100,0001 ≤ weights[i], durations[j] ≤ 10^9With 100,000 servers and 100,000 jobs, looking at every server for each job is 100,000 × 100,000 = 10,000,000,000 checks, far beyond the time limit.
Two heaps need about 4 heap steps for each job, at about 17 comparisons each. That is about 7 million steps.