Music streaming app~40 min2s · 256 MBtarget O(m x k log k) time, O(k) spacek-way-merge · heaps
A streaming service licenses titles in several regions. Each region has a shelf of titles, and the licence fee of each title is known. The shelves are sorted from the cheapest title to the dearest.
Marketing builds a bundle by taking exactly one title from every shelf. The total fee of a bundle is the sum of the fees of its titles. There are far too many bundles to list, so marketing asks for one number: the fee of the k-th cheapest bundle.
Write kth_cheapest_bundle(shelves, k).
shelves[s] is the list of fees on shelf s, in non-decreasing order.k, counting from 1.k at most the number of bundles.Input: shelves = [[1, 4, 6], [2, 3], [5, 9]], k = 4
Output: 12The trace folds in one shelf at a time, and keeps only the 4 cheapest totals so far.
| After shelf | The cheapest totals so far |
|---|---|
| none | 0 |
[1, 4, 6] |
1, 4, 6 |
[2, 3] |
3, 4, 6, 7 |
[5, 9] |
8, 9, 11, 12 |
The 4th cheapest total is 12, so the output is 12. The full list of bundle totals begins 8, 9, 11, 12, 12, 13, so the fifth bundle also costs 12.
Input: shelves = [[1, 1], [1]], k = 2
Output: 2Both bundles cost 2. They are two different bundles, so the 2nd cheapest costs 2.
Input: shelves = [[7, 8, 9]], k = 3
Output: 9With one shelf, a bundle is one title, and the 3rd cheapest is the 3rd fee.
1 ≤ shelves.length ≤ 40 (regions); each shelf has between 1 and 40 titles1 ≤ shelves[s][i] ≤ 1,000,000 (units), non-decreasing along a shelf1 ≤ k ≤ 200, and k is at most the product of the shelf sizesThe number of bundles is the product of the shelf sizes, and with 40 shelves of 40 titles that is 40^40, about 10^64. Listing and sorting them is impossible. But only the k cheapest totals matter, and k is at most 200. So combine the shelves one at a time, and after each shelf keep only the k cheapest totals.