Maximizing Unique Pairs from two arrays | 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
function findMaxPairs ( a , b , n , k ) { a . sort ( function ( c , d ) { return c - d ; } ) ; b . sort ( function ( c , d ) { return c - d ; } ) let flag = new Array ( n ) ; for ( let i = 0 ; i < flag . length ; i ++ ) { flag [ i ] = false ; } 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 ) { result ++ ; flag [ j ] = true ; break ; } } } 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 ) ) ;