Lets say I have two arrays A and B
A = {1,2,3}
B = {12,11,67}
and have max sum value S = 10
How many maximum number of unique pairs can be formed between the two arrays who's sum is less than or equal to S.
For e.g., the two possible values here are [1,11] [2,12] hence the answer is 2. If there are none, the answer is 0.
My solution was to sort both the arrays and then go do
if((Math.abs(A[i]-B[i]))<=S)
{
ans++;
}
Although it works for this case, clearly this is incorrect.
Best Answer
The key to doing this efficiently is exploiting the fact that if
a1 < a2
, thenpair(a2) \subseteq pair(a1)
, wherepair(a) = {b \in B : a + b <= S}
. Example Java code:This code assumes there are no duplicates in
A
orB
. The dominant operation is theO(n log n)
sort. The loop traverses each list once, so the overall complexity isO(n log n + 2n)
which is inO(n log n)
. If there are duplicates they can be removed from the sorted lists in linear time.