Maximizing Unique Pairs from two arrays | Java 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
import java . util . * ; class solution { static int findMaxPairs ( int a [ ] , int b [ ] , int n , int k ) { Arrays . sort ( a ) ; Arrays . sort ( b ) ; boolean [ ] flag = new boolean [ n ] ; Arrays . fill ( flag , false ) ; 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 ) { result ++ ; flag [ j ] = true ; break ; } } } return result ; } 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 ) ) ; } }