K Maximum Sum Combinations From Two Arrays

curriculum-track — k largest sums of a[i] + b[j], explored from (sorted top corner) outward via a max-heap.

Hard
Time O(k log k) Space O(k)
7 min read
top-k heaps

Problem#

(curriculum variant.) Given arrays a and b, return the k largest sums a[i] + b[j] over all (i, j).

Examples#

  • a = [1,4,2,3], b = [2,5,1,6], k = 4[10, 9, 9, 8]

Constraints#

  • 1 <= k <= len(a) * len(b).

Approach#

Sort both arrays descending. The largest sum is at (0, 0). From any (i, j), candidates for the next-largest are (i+1, j) and (i, j+1). Max-heap, visited set, pop k times.

Solution#

K Max Sum Combinations
vector<int> kMaxSumCombinations(vector<int> a, vector<int> b, int k) {
sort(a.rbegin(), a.rend());
sort(b.rbegin(), b.rend());
priority_queue<tuple<int,int,int>> pq;
set<pair<int,int>> seen;
pq.emplace(a[0] + b[0], 0, 0);
seen.insert({0, 0});
vector<int> ans;
while ((int)ans.size() < k && !pq.empty()) {
auto [s, i, j] = pq.top(); pq.pop();
ans.push_back(s);
if (i + 1 < (int)a.size() && !seen.count({i + 1, j})) {
pq.emplace(a[i + 1] + b[j], i + 1, j);
seen.insert({i + 1, j});
}
if (j + 1 < (int)b.size() && !seen.count({i, j + 1})) {
pq.emplace(a[i] + b[j + 1], i, j + 1);
seen.insert({i, j + 1});
}
}
return ans;
}

Editorial#

Mirror of Find K Pairs With Smallest Sums but in descending order. Same grid-expansion principle: at any (i, j), the candidates for the next-largest are its right and down neighbors in the descending-sorted grid.

Complexity#

  • Time: O(k log k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.