Maximize count of pairs ( i , j ) from two arrays having element from first array not exceeding that from second array | Java program for the above approach ; Function to return the maximum number of required pairs ; Max Heap to add values of arr2 [ ] ; Sort the array arr1 [ ] ; Push all arr2 [ ] into Max Heap ; Initialize the ans ; Traverse the arr1 [ ] in decreasing order ; Remove element until a required pair is found ; Return maximum number of pairs ; Driver Code ; Given arrays ; Function call
import java . io . * ; import java . util . * ; class GFG { static int numberOfPairs ( int [ ] arr1 , int n , int [ ] arr2 , int m ) { PriorityQueue < Integer > pQueue = new PriorityQueue < Integer > ( new Comparator < Integer > ( ) { public int compare ( Integer lhs , Integer rhs ) { if ( lhs < rhs ) { return + 1 ; } if ( lhs . equals ( rhs ) ) { return 0 ; } return - 1 ; } } ) ; int i , j ; Arrays . sort ( arr1 ) ; for ( j = 0 ; j < m ; j ++ ) { pQueue . add ( arr2 [ j ] ) ; } int ans = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( pQueue . peek ( ) >= 2 * arr1 [ i ] ) { ans ++ ; pQueue . poll ( ) ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr1 = { 3 , 1 , 2 } ; int [ ] arr2 = { 3 , 4 , 2 , 1 } ; int N = 3 ; int M = 4 ; System . out . println ( numberOfPairs ( arr1 , N , arr2 , M ) ) ; } }