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
EDIT: This does not work. I leave the answer, since apparently I am not the only one who could have this kind of idea; see the discussion below. A counter-example is x = (2, 3, 6), y = (1, 4, 5) and k=3, where the algorithm gives 7 (3+4) instead of 8 (3+5).
Let x
and y
be the two arrays, sorted in decreasing order; we want to construct the K
-th largest sum.
The variables are: i
the index in the first array (element x[i]
), j
the index in the second array (element y[j]
), and k
the "order" of the sum (k
in 1..K
), in the sense that S(k)=x[i]+y[j]
will be the k
-th greater sum satisfying your conditions (this is the loop invariant).
Start from (i, j)
equal to (0, 0)
: clearly, S(1) = x[0]+y[0]
.
for k
from 1
to K-1
, do:
x[i+1]+ y[j] > x[i] + y[j+1]
, then i := i+1
(and j
does not change) ; else j:=j+1
To see that it works, consider you have S(k) = x[i] + y[j]
. Then, S(k+1)
is the greatest sum which is lower (or equal) to S(k)
, and such as at least one element (i
or j
) changes. It is not difficult to see that exactly one of i
or j
should change.
If i
changes, the greater sum you can construct which is lower than S(k)
is by setting i=i+1
, because x
is decreasing and all the x[i'] + y[j]
with i' < i
are greater than S(k)
. The same holds for j
, showing that S(k+1)
is either x[i+1] + y[j]
or x[i] + y[j+1]
.
Therefore, at the end of the loop you found the K
-th greater sum.