1750. Top Selection Sums

Hard7.5 points estimatedHeapSortingGreedy

A treasure hunter may take any subset of the items described by nums, where each value is the (possibly negative) worth of one item; taking nothing is allowed and is worth 0. Two different choices of items count separately even if their totals are equal. List the totals of all 2^n subsets in non-increasing order and return the first k of them as a long[]. The number of subsets is far too large to enumerate, so the intended solution runs in O(n log n + k log k) time and O(n + k) space. Values can be as large as 10^9 in magnitude, so totals need 64-bit integers. Here n is at most 10^5 and k is at most 2000.

Example 1

Input:
nums = [3,-1,2], k = 5
Output:
[5,4,3,2,2]
Explanation:

The eight subset sums are 5, 4, 3, 2, 2, 1, 0 and -1 in descending order, so the top five are 5, 4, 3, 2, 2.

Example 2

Input:
nums = [0,0], k = 4
Output:
[0,0,0,0]
Explanation:

Every subset sums to 0 and there are four subsets, so the answer is four zeros.

Constraints

1 ≤ n = nums.length ≤ 105; -109 ≤ nums[i] ≤ 109; 1 ≤ k ≤ min(2000, 2^n).

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n log n + k log k)
Space
O(n + k)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…