Maximizing Unique Pairs from two arrays | C ++ implementation of above approach ; Returns count of maximum pairs that caan be formed from a [ ] and b [ ] under given constraints . ; Sorting the first array . ; Sorting the second array . ; To keep track of visited elements of b [ ] ; For every element of a [ ] , find a pair for it and break as soon as a pair is found . ; Increasing the count if a pair is formed . ; Making the corresponding flag array element as 1 indicating the element in the second array element has been used . ; We break the loop to make sure an element of a [ ] is used only once . ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll  long long int NEW_LINE using namespace std ; ll findMaxPairs ( ll a [ ] , ll b [ ] , ll n , ll k ) { sort ( a , a + n ) ; sort ( b , b + n ) ; bool flag [ n ] ; memset ( flag , false , sizeof ( flag ) ) ; 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 ) { result ++ ; flag [ j ] = true ; break ; } } } return result ; } 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 ; }