Music streaming app~35 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1383greedy · heaps · sorting
A music streaming app runs encoder servers that convert uploaded tracks. Each server has a speed, in tracks an hour, and a quality score.
A group of servers works on one batch of uploads. The group runs at the speed of all its servers added together, and it must use the lowest quality score of its members. Your team lead says: "Pick a group of at most k servers with the highest throughput, where throughput is the total speed times the lowest quality." The pool can hold 100,000 servers.
Write best_throughput(speeds, qualities, k).
speeds[i] and qualities[i] describe server i. Both lists have the same length.k different servers.(sum of speeds in the group) × (minimum of qualities in the group).int.Input: speeds = [2, 10, 3, 1, 9], qualities = [5, 4, 3, 9, 2], k = 3
Output: 52Go through the servers from the highest quality to the lowest. Keep the speeds of the best k servers in a min-heap. After adding a server, if the heap has more than k, give back the smallest speed. The current quality is the lowest in the group, so the throughput is the total speed times it.
| Server added (speed, quality) | Heap after (speeds) | Total speed | Throughput |
|---|---|---|---|
| (1, 9) | 1 | 1 | 1 × 9 = 9 |
| (2, 5) | 1, 2 | 3 | 3 × 5 = 15 |
| (10, 4) | 1, 2, 10 | 13 | 13 × 4 = 52 |
| (3, 3) | 2, 3, 10, after giving back 1 | 15 | 15 × 3 = 45 |
| (9, 2) | 3, 9, 10, after giving back 2 | 22 | 22 × 2 = 44 |
The highest throughput is 52.
Input: speeds = [10, 1], qualities = [10, 1], k = 2
Output: 100Both servers together give 11 × 1 = 11. The first server alone gives 10 × 10 = 100. A smaller group can be better.
Input: speeds = [4, 9, 6], qualities = [8, 2, 5], k = 1
Output: 32One server: 4 × 8 = 32, 9 × 2 = 18 and 6 × 5 = 30. The best is 32.
1 ≤ length of speeds = length of qualities ≤ 10^5, and 1 ≤ speeds[i], qualities[i] ≤ 10001 ≤ k ≤ length of speedsThe number of groups of up to k servers is about n choose k or more. For n = 100,000 and k = 30,000 that is a number with 26,500 digits.
Sorting by quality costs about 100,000 × 17 steps, and the heap costs the same. The total speed reaches 10^8 and the throughput 10^11, so the throughput needs a 64-bit integer.