![]() |
VOOZH | about |
Given two arrays of equal size N, form maximum number of pairs by using their elements, one from the first array and second from the second array, such that an element from each array is used at-most-once and the absolute difference between the selected elements used for forming a pair is less than or equal to a given element K.
Examples:
Input : a[] = {3, 4, 5, 2, 1}
b[] = {6, 5, 4, 7, 15}
k = 3
Output : 4
The maximum number of pairs that can be formed
using the above 2 arrays is 4 and the corresponding
pairs are [1, 4], [2, 5], [3, 6], [4, 7], we can't
pair the remaining elements.
Other way of pairing under given constraint is
[2, 5], [3, 6], [4, 4], but count of pairs here
is 3 which is less than the result 4.
Simple Approach: By taking few examples, we can observe that if we sort both arrays. Then one by picking the closest feasible element for every element, we get the optimal answer.
In this approach we first sort both the arrays and then compare each element of the first array with each element of the second array for the possible pair, if it's possible to form a pair, we form the pair and move to check for the next possible pair for the next element of the first array.
Implementation:
2
Time complexity : O(n2)
Auxiliary Space : O(n)
Efficient Approach: In this approach, rather than checking all the possible combinations of pairs, we optimize our code by checking only the feasible combination of pairs using the 2 pointer approach.
Implementation:
2
Time complexity : O(n Log n)
Auxiliary Space : O(1)