DEV Community

Jaspreet singh
Jaspreet singh

Posted on

Maximum Sum Combinations

Problem Statement

Given two arrays:

A[]
B[]
Enter fullscreen mode Exit fullscreen mode

Find the top K maximum values of:

A[i] + B[j]
Enter fullscreen mode Exit fullscreen mode

Brute Force Intuition

Generate every possible pair:

A[i] + B[j]
Enter fullscreen mode Exit fullscreen mode

Store all sums.

Sort.

Take top K.

Complexity

  • Time Complexity: O(N² log N²)
  • Space Complexity: O(N²)

Brute Force Code

for(i)
   for(j)
      sums.add(A[i] + B[j]);

Collections.sort(sums);
Enter fullscreen mode Exit fullscreen mode

Better Approach (Your Code)

Keep only K largest sums using a Min Heap.

PriorityQueue<Integer> pq =
    new PriorityQueue<>();
Enter fullscreen mode Exit fullscreen mode

Generate all pairs.

If heap size exceeds K:

pq.poll();
Enter fullscreen mode Exit fullscreen mode

Complexity

Metric Complexity
Time O(N² log K)
Space O(K)

Moving Towards Optimal

Observation:

After sorting:

Largest pair

=
Largest A
+
Largest B
Enter fullscreen mode Exit fullscreen mode

Suppose:

A = [1,4,2,3]

B = [2,5,1,6]
Enter fullscreen mode Exit fullscreen mode

Sort:

A = [1,2,3,4]

B = [1,2,5,6]
Enter fullscreen mode Exit fullscreen mode

Largest sum:

4 + 6 = 10
Enter fullscreen mode Exit fullscreen mode

After taking:

(i,j)
Enter fullscreen mode Exit fullscreen mode

next candidates are:

(i-1,j)

(i,j-1)
Enter fullscreen mode Exit fullscreen mode

This becomes identical to:

Merge K Sorted Lists
Enter fullscreen mode Exit fullscreen mode

and can be solved using:

Max Heap + Visited Set
Enter fullscreen mode Exit fullscreen mode

Optimal Complexity

Metric Complexity
Time O(K log K)
Space O(K)

Interview One-Liner

Sort both arrays, start from the maximum pair, and use a Max Heap with a visited set to generate only the next best K sums.


Pattern Learned

Top K Pair Values

=> Max Heap
=> Visited Set
=> Sorted Arrays
Enter fullscreen mode Exit fullscreen mode

Top comments (0)