Maximize count of persons receiving a chocolate | C ++ program for the above approach ; Function to count the maximum number of persons receiving a chocolate ; Initialize count as 0 ; Sort the given arrays ; Initialize a multiset ; Insert B [ ] array values into the multiset ; Traverse elements in array A [ ] ; Search for the lowest value in B [ ] ; If found , increment count , and delete from set ; Return the number of people ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxPersons ( int * A , int n , int * B , int m , int x ) { int count = 0 ; sort ( A , A + n ) ; sort ( B , B + m ) ; multiset < int > s ; for ( int i = 0 ; i < m ; i ++ ) s . insert ( B [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { int val = A [ i ] - x ; auto it = s . lower_bound ( val ) ; if ( it != s . end ( ) && * it <= A [ i ] + x ) { count ++ ; s . erase ( it ) ; } } return count ; } int main ( ) { int A [ ] = { 90 , 49 , 20 , 39 , 49 } ; int B [ ] = { 14 , 24 , 82 } ; int X = 15 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << countMaxPersons ( A , N , B , M , X ) ; }