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
The pairs with largest sums are:
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.
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.
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 .
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).
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.
max.i + 1 < a.length
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With