Maximizing Unique Pairs from two arrays
Last Updated :
19 Sep, 2023
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:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
ll findMaxPairs(ll a[], ll b[], ll n, ll k)
{
sort(a, a+n); // Sorting the first array.
sort(b, b+n); // Sorting the second array.
// To keep track of visited elements of b[]
bool flag[n];
memset(flag, false, sizeof(flag));
// For every element of a[], find a pair
// for it and break as soon as a pair is
// found.
int result = 0;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (abs(a[i]-b[j])<=k && flag[j]==false)
{
// Increasing the count if a pair is formed.
result++;
/* Making the corresponding flag array
element as 1 indicating the element
in the second array element has
been used. */
flag[j] = true;
// We break the loop to make sure an
// element of a[] is used only once.
break;
}
}
}
return result;
}
// Driver code
int main()
{
ll a[] = {10, 15, 20}, b[] = {17, 12, 24};
int n = sizeof(a)/sizeof(a[0]);
int k = 3;
cout << findMaxPairs(a, b, n, k);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
class solution
{
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
static int findMaxPairs(int a[], int b[], int n, int k)
{
Arrays.sort(a); // Sorting the first array.
Arrays.sort(b); // Sorting the second array.
// To keep track of visited elements of b[]
boolean []flag = new boolean[n];
Arrays.fill(flag,false);
// For every element of a[], find a pair
// for it and break as soon as a pair is
// found.
int result = 0;
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (Math.abs(a[i]-b[j])<=k && flag[j]==false)
{
// Increasing the count if a pair is formed.
result++;
/* Making the corresponding flag array
element as 1 indicating the element
in the second array element has
been used. */
flag[j] = true;
// We break the loop to make sure an
// element of a[] is used only once.
break;
}
}
}
return result;
}
// Driver code
public static void main(String args[])
{
int[] a = {10, 15, 20};
int[] b = {17, 12, 24};
int n = a.length;
int k = 3;
System.out.println(findMaxPairs(a, b, n, k));
}
}
// This code is contributed by
// Shashank_Sharma
Python 3
# Returns count of maximum pairs
# that can be formed from a[] and
# b[] under given constraints.
def findMaxPairs(a, b, n, k):
a.sort() # Sorting the first array.
b.sort() # Sorting the second array.
# To keep track of visited
# elements of b[]
flag = [False] * n
# For every element of a[], find
# a pair for it and break as soon
# as a pair is found.
result = 0
for i in range(n):
for j in range(n):
if (abs(a[i] - b[j]) <= k and
flag[j] == False):
# Increasing the count if
# a pair is formed.
result += 1
''' Making the corresponding flag array
element as 1 indicating the element
in the second array element has
been used. '''
flag[j] = True
# We break the loop to make sure an
# element of a[] is used only once.
break
return result
# Driver code
if __name__ == "__main__":
a = [10, 15, 20]
b = [17, 12, 24]
n = len(a)
k = 3
print(findMaxPairs(a, b, n, k))
# This code is contributed
# by ChitraNayal
C#
// C# implementation of above approach
using System;
class GFG
{
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
static int findMaxPairs(int []a, int []b,
int n, int k)
{
Array.Sort(a); // Sorting the first array.
Array.Sort(b); // Sorting the second array.
// To keep track of visited elements of b[]
bool []flag = new bool[n];
//Arrays.fill(flag,false);
// For every element of a[], find a pair
// for it and break as soon as a pair is
// found.
int result = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.Abs(a[i] - b[j]) <= k && flag[j] == false)
{
// Increasing the count if a pair is formed.
result++;
/* Making the corresponding flag array
element as 1 indicating the element
in the second array element has
been used. */
flag[j] = true;
// We break the loop to make sure an
// element of a[] is used only once.
break;
}
}
}
return result;
}
// Driver code
public static void Main()
{
int[] a = {10, 15, 20};
int[] b = {17, 12, 24};
int n = a.Length;
int k = 3;
Console.WriteLine(findMaxPairs(a, b, n, k));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript implementation of above approach
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
function findMaxPairs(a,b,n,k)
{
a.sort(function(c,d){return c-d;}); // Sorting the first array.
b.sort(function(c,d){return c-d;}) // Sorting the second array.
// To keep track of visited elements of b[]
let flag = new Array(n);
for(let i=0;i<flag.length;i++)
{
flag[i]=false;
}
// For every element of a[], find a pair
// for it and break as soon as a pair is
// found.
let result = 0;
for (let i=0; i<n; i++)
{
for (let j=0; j<n; j++)
{
if (Math.abs(a[i]-b[j])<=k && flag[j]==false)
{
// Increasing the count if a pair is formed.
result++;
/* Making the corresponding flag array
element as 1 indicating the element
in the second array element has
been used. */
flag[j] = true;
// We break the loop to make sure an
// element of a[] is used only once.
break;
}
}
}
return result;
}
// Driver code
let a=[10, 15, 20];
let b=[17, 12, 24];
let n = a.length;
let k = 3;
document.write(findMaxPairs(a, b, n, k));
// This code is contributed by rag2127
</script>
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:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
ll findMaxPairs(ll a[], ll b[], ll n, ll k)
{
sort(a, a+n); // Sorting the first array.
sort(b, b+n); // Sorting the second array.
int result = 0;
for (int i=0, j=0; i<n && j<n;)
{
if (abs(a[i] - b[j]) <= k)
{
result++;
// Increasing array pointer of
// both the first and the second array.
i++;
j++;
}
// Increasing array pointer of the second array.
else if(a[i] > b[j])
j++;
// Increasing array pointer of the first array.
else
i++;
}
return result;
}
// Driver code
int main()
{
ll a[] = {10, 15, 20};
ll b[] = {17, 12, 24};
int n = sizeof(a)/sizeof(a[0]);
int k = 3;
cout << findMaxPairs(a, b, n, k);
return 0;
}
Java
// Java program for Maximizing Unique Pairs
// from two arrays
import java.util.*;
class GFG
{
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
static int findMaxPairs(int a[], int b[],
int n, int k)
{
Arrays.sort(a); // Sorting the first array.
Arrays.sort(b); // Sorting the second array.
int result = 0;
for (int i = 0, j = 0; i < n && j < n;)
{
if (Math.abs(a[i] - b[j]) <= k)
{
result++;
// Increasing array pointer of
// both the first and the second array.
i++;
j++;
}
// Increasing array pointer
// of the second array.
else if(a[i] > b[j])
j++;
// Increasing array pointer
// of the first array.
else
i++;
}
return result;
}
// Driver code
public static void main(String args[])
{
int a[] = {10, 15, 20};
int b[] = {17, 12, 24};
int n = a.length;
int k = 3;
System.out.println(findMaxPairs(a, b, n, k));
}
}
// This code is contributed by
// Sanjit_Prasad
Python3
# Python3 program for
# Maximizing Unique Pairs
# from two arrays
# Returns count of maximum pairs that can
# be formed from a[] and b[] under given
# constraints.
def findMaxPairs(a,b,n,k):
# Sorting the first array.
a.sort()
# Sorting the second array.
b.sort()
result =0
j=0
for i in range(n):
if j<n:
if abs(a[i]-b[j])<=k:
result+=1
# Increasing array pointer of
# both the first and the second array.
j +=1
# Increasing array pointer of
# the second array.
elif a[i]>b[j]:
j+=1
return result
# Driver code
if __name__=='__main__':
a = [10,15,20]
b = [17,12,24]
n = len(a)
k =3
print(findMaxPairs(a,b,n,k))
# This code is contributed by
# Shrikant13
C#
// C# program for Maximizing Unique Pairs
// from two arrays
using System;
class GFG
{
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
static int findMaxPairs(int []a, int []b,
int n, int k)
{
Array.Sort(a); // Sorting the first array.
Array.Sort(b); // Sorting the second array.
int result = 0;
for (int i = 0, j = 0; i < n && j < n;)
{
if (Math.Abs(a[i] - b[j]) <= k)
{
result++;
// Increasing array pointer of
// both the first and the second array.
i++;
j++;
}
// Increasing array pointer
// of the second array.
else if(a[i] > b[j])
j++;
// Increasing array pointer
// of the first array.
else
i++;
}
return result;
}
// Driver code
public static void Main(String []args)
{
int []a = {10, 15, 20};
int []b = {17, 12, 24};
int n = a.Length;
int k = 3;
Console.WriteLine(findMaxPairs(a, b, n, k));
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program for Maximizing
// Unique Pairs from two arrays
// Returns count of maximum pairs that can
// be formed from a[] and b[] under given
// constraints.
function findMaxPairs(a, b, n, k)
{
// Sorting the first array.
a.sort(function(a, b){return a - b});
// Sorting the second array.
b.sort(function(a, b){return a - b});
let result = 0;
for (let i = 0, j = 0; i < n && j < n;)
{
if (Math.abs(a[i] - b[j]) <= k)
{
result++;
// Increasing array pointer of
// both the first and the second array.
i++;
j++;
}
// Increasing array pointer
// of the second array.
else if(a[i] > b[j])
j++;
// Increasing array pointer
// of the first array.
else
i++;
}
return result;
}
let a = [10, 15, 20];
let b = [17, 12, 24];
let n = a.length;
let k = 3;
document.write(findMaxPairs(a, b, n, k));
</script>
Time complexity : O(n Log n)
Auxiliary Space : O(1)
Similar Reads
Pair with maximum GCD from two arrays Given two arrays of n integers with values of the array being small (values never exceed a small number say 100). Find the pair(x, y) which has maximum gcd. x and y cannot be of the same array. If multiple pairs have the same gcd, then consider the pair which has the maximum sum. Examples: Input : a
15+ min read
Find Sum of pair from two arrays with maximum sum Given two arrays of positive and distinct integers. The task is to find a pair from the two arrays with maximum sum. Note: The pair should contain one element from both the arrays. Examples: Input : arr1[] = {1, 2, 3}, arr2[] = {4, 5, 6} Output : Max Sum = 9 Pair (3, 6) has the maximum sum. Input :
6 min read
Maximum Sum Path in Two Arrays Given two sorted arrays having some elements in common. Find the sum of the maximum sum path to reach from the beginning of any array to the end of any of the two arrays. We can switch from one array to another array only at common elements. Note: The common elements do not have to be at the same in
14 min read
Maximum possible pair sum at most K from two Arrays Given two arrays arr1[] and arr2[] of sizes N and M and an integer K, the task is to find the maximum possible sum pair from two arrays such that the sum is at most K. Note: You have to take one element from each array. Examples: Input: arr1[] = {5, 4, 1, 2, 3}, arr2[] = {30, 20, 40, 10}, K = 30Outp
12 min read
Maximum sum combination from two arrays Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both arrays such that no two elements have the same index and no two consecutive numbers can be selected from a single array. Find the maximum sum possible of the above-chosen numbers. Examples: Input : arr1[
10 min read