Ad platform~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-2542greedy · heaps · sorting
An ad platform sells slots on a page. Each slot has a reach, in thousands of viewers, and a quality rating. A campaign buys exactly k slots.
The value of a campaign is the total reach of its slots, multiplied by the lowest quality among them. Your team lead says: "Find the campaign of k slots with the highest value." A page can offer 100,000 slots, so the team cannot test every set of k slots.
Write best_ad_score(reach, quality, k).
reach[i] and quality[i] describe slot i. Both lists have the same length.k different slots.(sum of reach over the chosen slots) × (minimum of quality over the chosen slots).k slots. It can pass the range of an int.Input: reach = [6, 1, 8, 2, 5, 3], quality = [2, 9, 4, 6, 3, 8], k = 3
Output: 52Go through the slots from the highest quality to the lowest. Keep the reach values of the best k slots in a min-heap. After adding a slot, if the heap has more than k, give back the smallest reach. With exactly k slots, the current quality is the lowest, so the value is the total reach times it.
| Slot added (reach, quality) | Heap after (reach values) | Total reach | Value |
|---|---|---|---|
| (1, 9) | 1 | 1 | not yet k slots |
| (3, 8) | 1, 3 | 4 | not yet k slots |
| (2, 6) | 1, 2, 3 | 6 | 6 × 6 = 36 |
| (8, 4) | 2, 3, 8, after giving back 1 | 13 | 13 × 4 = 52 |
| (5, 3) | 3, 5, 8, after giving back 2 | 16 | 16 × 3 = 48 |
| (6, 2) | 5, 6, 8, after giving back 3 | 19 | 19 × 2 = 38 |
The best value is 52.
Input: reach = [4, 2, 6, 3, 5], quality = [3, 7, 2, 5, 4], k = 3
Output: 40The slots with quality 7, 5 and 4 have reach 2, 3 and 5. The total reach is 10, and the lowest quality is 4, so the value is 40. No other three slots do better.
Input: reach = [5, 9], quality = [4, 2], k = 1
Output: 20One slot: the value is 5 × 4 = 20 for the first slot and 9 × 2 = 18 for the second.
1 ≤ length of reach = length of quality ≤ 10^5, and 0 ≤ reach[i], quality[i] ≤ 10^51 ≤ k ≤ length of reachThe number of sets of k slots is n choose k. For n = 100,000 and k = 30,000 that is a number with about 26,500 digits.
Sorting by quality costs about 100,000 × 17 steps, and the heap costs the same. The total reach reaches 10^10 and the value 10^15, so the value needs a 64-bit integer.