Maximize count of pairs ( i , j ) from two arrays having element from first array not exceeding that from second array | C ++ program for the above approach ; Function to return the maximum number of required pairs ; Max Heap to add values of arar2 [ ] ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfPairs ( int arr1 [ ] , int n , int arr2 [ ] , int m ) { priority_queue < int > pq ; int i , j ; sort ( arr1 , arr1 + n ) ; for ( j = 0 ; j < m ; j ++ ) { pq . push ( arr2 [ j ] ) ; } int ans = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( pq . top ( ) >= 2 * arr1 [ i ] ) { ans ++ ; pq . pop ( ) ; } } return ans ; } int main ( ) { int arr1 [ ] = { 3 , 1 , 2 } ; int arr2 [ ] = { 3 , 4 , 2 , 1 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << numberOfPairs ( arr1 , N , arr2 , M ) ; return 0 ; }