GeeksforGeeks Medium

Maximum Sum Combination

Maximum Sum Combination is a GFG problem (Medium). You are given two integer arrays a and b of the same length n, and an integer k.

  • A sum combination is a[i] + b[j] for one index pair (i, j); each pair is used at most once.
  • Return the top k sums, largest first. Equal sums from different pairs are listed separately.
  • n goes up to 10⁵, so there are up to 10¹⁰ pairs. Building them all is far too slow.
Constraints
  • 1 <= n <= 10⁵ (a and b have the same length)
  • 1 <= a[i], b[i] <= 10⁴
  • 1 <= k <= n
heaparray
Open on GeeksforGeeks ↗
02

Intuition

Sort both arrays from largest to smallest and picture every sum in a grid: row i is a[i], column j is b[j], and cell (i, j) holds a[i] + b[j].

  • Biggest: the top-left cell (0, 0) holds the largest sum.
  • Order: sums shrink as you move right or down, because each step swaps in a smaller number.
  • Next candidates: so after taking a cell, the only new cells that can be next are the one below it and the one to its right.

A max-heap holds these candidate cells and always gives back the largest. Each of the k pops adds at most two cells, so only about 2k of the n² cells are ever looked at.

How to spot this pattern

Use this frontier-with-a-heap idea when you need the k best (or k smallest) values from something sorted along two directions: the k largest pair sums of two arrays, a row- and column-sorted matrix, or k pairs with the smallest sums.

03

Approach

Try it first

Before reading on: after sorting both arrays in descending order, which pair gives the largest sum? Once you take it, which two pairs could give the second largest? What goes wrong if two different cells both point to the same next cell?

1

Sort both arrays in descending order

Now a[0] + b[0] is the largest sum, and every sum gets smaller as i or j grows. This ordering is what lets the search look only at neighbours instead of all n² pairs.

2

Start the heap at the corner

Push (a[0] + b[0], 0, 0) onto a max-heap and add (0, 0) to a seen set.

3

Pop the largest sum

Pop the top of the heap and append its sum to the result. It is the largest sum not yet taken: every cell not looked at yet lies below or to the right of some cell in the heap, so it cannot be bigger.

4

Push the cell below and the cell to the right

For (i + 1, j) and (i, j + 1):

  • skip it if the index runs past the end of the array;
  • skip it if it is already in seen;
  • otherwise add it to seen and push its sum.

Most cells sit next to two taken cells, one above and one to the left, so seen makes sure each cell enters the heap only once.

5

Stop after k pops

The result already holds the k largest sums in order from largest to smallest, so return it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def topKSumPairs(self, a, b, k):
▶3 a.sort(reverse=True)
▶4 b.sort(reverse=True)
▶5 heap = [(-(a[0] + b[0]), 0, 0)]
▶6 seen = {(0, 0)}
▶7 res = []
▶8 while len(res) < k:
▶9 s, i, j = heapq.heappop(heap)
▶10 res.append(-s)
▶11 for ni, nj in ((i + 1, j), (i, j + 1)):
▶12 if ni < len(a) and nj < len(b) and (ni, nj) not in seen:
▶13 seen.add((ni, nj))
▶14 heapq.heappush(heap, (-(a[ni] + b[nj]), ni, nj))
▶15 return res
ba4132heapemptyresultsort a and b from largest to smallest
a[3, 2]was [3, 2]
b[4, 1]was [1, 4]
k2sums wanted
Sort both arrays, largest first. Cell (i, j) of the grid is a[i] + b[j]. After sorting, every step right or down swaps in a smaller number, so sums only shrink in those directions. No sum has been worked out yet, so every cell is still dashed.
ba41372heap7(0, 0)resultpush corner (0, 0): 3 + 4 = 7
heap[7]cell (0, 0)
seen{(0, 0)}
The top-left cell adds the two largest numbers, so it is the largest sum. It is the only cell the heap needs to start with, and it is marked as seen.
ba41372heapemptyresult7pop 7 at (0, 0) → result #1
popped7cell (0, 0)
result[7]1 of 2
Pop 7. It is the largest sum in the heap, and every dashed cell lies below or to the right of a heap cell, so none of them can be larger. Now its two neighbours become candidates.
ba413726heap6(1, 0)result7push (1, 0): 2 + 4 = 6
cell(1, 0)below
sum62 + 4
heap size1
The cell below is new: mark it seen and push its sum, 6. It may be the next largest, because it is only one step away from a cell already taken.
ba4137426heap6(1, 0)4(0, 1)result7push (0, 1): 3 + 1 = 4
cell(0, 1)to the right
sum43 + 1
heap size2
The cell to the right is new: mark it seen and push its sum, 4. It may be the next largest, because it is only one step away from a cell already taken.
ba4137426heap4(0, 1)result76pop 6 at (1, 0) → result #2
popped6cell (1, 0)
result[7, 6]2 of 2
Pop 6. It is the largest sum in the heap, and every dashed cell lies below or to the right of a heap cell, so none of them can be larger. That makes 2 sums; the loop body still checks its two neighbours, then the while condition ends the loop.
ba4137426noneheap4(0, 1)result76(2, 0) is past the end of a → skip
cell(2, 0)out of range
The cell below would need a[2], but the array has only 2 numbers. There is no such pair, so nothing is pushed.
ba41374263heap4(0, 1)3(1, 1)result76push (1, 1): 2 + 1 = 3
cell(1, 1)to the right
sum32 + 1
heap size2
The cell to the right is new: mark it seen and push its sum, 3. It may be the next largest, because it is only one step away from a cell already taken.
ba41374263heap4(0, 1)3(1, 1)result76return [7, 6]
result[7, 6]largest first
Done after 2 pops. In a grid this small every cell got computed, but each was looked at only once. On large arrays with k much smaller than n², most of the grid never is.
05

Common pitfalls

Building every sum first

✗ Wrong
sums = sorted((x + y for x in a for y in b), reverse=True)
return sums[:k]
✓ Right
heap = [(-(a[0] + b[0]), 0, 0)]
# grow only the frontier

With n = 10⁵ that is 10¹⁰ sums, far beyond the time and memory limits. The heap touches only about 2k cells.

Leaving out the seen set

✗ Wrong
for ni, nj in ((i + 1, j), (i, j + 1)):
    heapq.heappush(heap, (-(a[ni] + b[nj]), ni, nj))
✓ Right
if (ni, nj) not in seen:
    seen.add((ni, nj))
    heapq.heappush(heap, (-(a[ni] + b[nj]), ni, nj))

Cell (1, 1) is the neighbour of both (0, 1) and (1, 0). Without the check it is pushed twice and its sum appears twice in the answer.

Storing raw sums in Python's heapq

✗ Wrong
heap = [(a[0] + b[0], 0, 0)]
✓ Right
heap = [(-(a[0] + b[0]), 0, 0)]

heapq always pops the smallest item, so raw sums come out smallest first. Negate on the way in and again on the way out.

06

Edge cases

Equal sums from different pairs

Each pair counts once, so equal sums are all listed: in a = [1, 4, 2, 3], b = [2, 5, 1, 6] the answer for k = 3 is [10, 9, 9]. The seen set stores index pairs, not sums, so it never drops a real tie.

07

Complexity

Time
O(n log n + k log k)
Space
O(k)
Sorting costs O(n log n). Each of the k pops adds at most two cells, so the heap and the seen set hold O(k) entries and each heap operation costs O(log k).
08

Related heap-on-a-grid problems

The same frontier idea solves all three; the direction and what you return change.

ProblemWantsStart cellHeap
Maximum Sum Combination (GFG)k largest sums a[i] + b[j]both arrays' largestmax-heap
Find K Pairs with Smallest Sums (LeetCode 373)k smallest pairs, as pairsboth arrays' smallestmin-heap
Kth Smallest Element in a Sorted Matrix (LeetCode 378)one value: the kth smallesttop-left of the matrixmin-heap
09

Maximum Sum Combination FAQ

What are the steps?
  • Sort: both arrays in descending order.
  • Start: push (a[0] + b[0], 0, 0) onto a max-heap and mark (0, 0) seen.
  • Repeat k times: pop the largest, add it to the answer, push (i + 1, j) and (i, j + 1) if they are in range and unseen.
  • Complexity: O(n log n + k log k) time, O(k) extra space.
Is this the same as the InterviewBit Maximum Sum Combinations problem?

Yes. InterviewBit's version asks for the C largest sums from two arrays of size N, which is the same task with k renamed to C. The same heap solution applies.