Find K-Sum Subsets

curriculum variant — return the k subsets with the largest sums, via heap-based BFS over subset construction.

Medium
Time O((n + k) log (n + k)) Space O(n + k)
7 min read
subsets heaps top-k

Problem#

(curriculum variant.) Given an array nums and an integer k, return the k subsets with the largest sums (each as a list).

Examples#

  • nums = [1, 2, 3], k = 4[[1,2,3], [2,3], [1,3], [3]]

Constraints#

  • 1 <= k <= 2^n.

Hints#

Hint 1
Sort descending. Max-heap holds (running sum, last-included index). Two children per pop: include next, or skip the included-last and include next.

Approach#

Sort nums descending. Max-heap of (sum, subset, lastIndex). Start with (0, [], -1) and the full subset is just adding the next available element. To avoid duplicates, restrict each pop’s expansions to indices > lastIndex; emit two branches: extend with next element, or swap last for next (Eppstein’s k-th shortest path expansion).

Solution#

K Largest Subset Sums
vector<vector<int>> kLargestSubsetSums(vector<int> nums, int k) {
sort(nums.rbegin(), nums.rend());
using State = tuple<long long, vector<int>, int>; // (-sum for min-heap order, subset, lastIdx)
priority_queue<State> pq;
pq.push({0LL, {}, -1});
vector<vector<int>> ans;
while (k-- > 0 && !pq.empty()) {
auto [sum, sub, last] = pq.top(); pq.pop();
ans.push_back(sub);
int nxt = last + 1;
if (nxt < (int)nums.size()) {
auto extended = sub; extended.push_back(nums[nxt]);
pq.push({sum + nums[nxt], extended, nxt});
if (!sub.empty()) {
auto swapped = sub; swapped.back() = nums[nxt];
pq.push({sum - nums[last] + nums[nxt], swapped, nxt});
}
}
}
return ans;
}

Editorial#

Identical structure to Find K-Sum of an Array. Sorting descending ensures that “extend with the next element” or “swap last for next” both produce sums that decrease — so heap-pop order yields subsets in descending sum order. Each subset is emitted exactly once via the no-overlap invariant on lastIndex.

Complexity#

  • Time: O((n + k) log (n + k) * n).
  • Space: O((n + k) * n) (subsets stored).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.