Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the pair across 2 arrays with kth largest sum [closed]

Given two sorted arrays of numbers, we want to find the pair with the kth largest possible sum. A pair is one element from the first array and one element from the second array. For example, with arrays

  • [2, 3, 5, 8, 13]
  • [4, 8, 12, 16]

The pairs with largest sums are:

  1. 13 + 16 = 29
  2. 13 + 12 = 25
  3. 8 + 16 = 24
  4. 13 + 8 = 21
  5. 8 + 12 = 20

So the pair with the 4th largest sum is (13, 8). How to find the pair with the kth largest possible sum?

I anticipate the solution may involve either a min heap or a max heap.

like image 323
TimeToCodeTheRoad Avatar asked Mar 06 '11 17:03

TimeToCodeTheRoad


People also ask

How do you find the kth largest element in a sorted array?

It can be clearly observed that Kth largest element is the same as (N – K)th smallest element, where N is the size of the given array. Therefore, we can apply the Kth smallest approach to this problem.

How do you find the maximum sum of two numbers in an array?

The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (1,5) , (2,3) , and (4,4) , the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 .

How do I find the kth element in a sorted array?

Merge the Two Arrays. Similar to one single step of the Merge Sort sorting algorithm, we can merge the two arrays and then directly retrieve the kth element. The basic idea of the merge algorithm is to start with two pointers, which point to the first elements of the first and second arrays (a).


1 Answers

That can be easily done in O(k*logk). I'll only assume arrays are sorted in descending order, to simplify notation.

The idea is simple. We'll find 1st, 2nd, .., k-th maximum values one by one. But to even consider pair (i, j) we need to have both (i-1, j) and (i, j-1) already selected, because they both are greater or equal than (i, j).

It's much like if we push all n*m pairs into the heap and then remove max k times. Only we don't need all n*m pairs.

heap.add(pair(0, 0));  // biggest pair

// remove max k-1 times
for (int i = 0; i < k - 1; ++i) {
    // get max and remove it from the heap
    max = heap.popMax();

    // add next candidates
    heap.add(pair(max.i + 1, max.j));
    heap.add(pair(max.i, max.j + 1));
}

// get k-th maximum element
max = heap.popMax();
maxVal = a[max.i] + b[max.j];

Some things to consider.

  • Duplicated pairs can be added to the heap, this can be prevented with hash.
  • Indexes need to be validated, e.g. that max.i + 1 < a.length.
like image 139
Nikita Rybak Avatar answered Oct 14 '22 03:10

Nikita Rybak