Distribution of candies according to ages of students | C ++ implementation of the approach ; Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; Creating the frequency array of the age of students ; Creating the frequency array of the packets of candies ; Pointer to tell whether we have reached the end of candy frequency array ; Flag to tell if distribution is possible or not ; Flag to tell if we can choose some candy packets for the students with age j ; If the quantity of packets is greater than or equal to the number of students of age j , then we can choose these packets for the students ; Start searching from k + 1 in next operation ; If we cannot choose any packets then the answer is NO ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check_distribution ( int n , int k , int age [ ] , int candy [ ] ) { int mxage = * ( std :: max_element ( age , age + n ) ) + 1 ; int mxcandy = * ( std :: max_element ( candy , candy + k ) ) + 1 ; int fr1 [ mxage ] = { 0 } ; int fr2 [ mxcandy ] = { 0 } ; for ( int j = 0 ; j < n ; j ++ ) { fr1 [ age [ j ] ] += 1 ; } for ( int j = 0 ; j < k ; j ++ ) { fr2 [ candy [ j ] ] += 1 ; } k = 0 ; bool Tf = true ; for ( int j = 0 ; j < mxage ; j ++ ) { if ( fr1 [ j ] == 0 ) continue ; bool flag = false ; while ( k < mxcandy ) { if ( fr1 [ j ] <= fr2 [ k ] ) { flag = true ; break ; } k += 1 ; } k = k + 1 ; if ( flag == false ) { Tf = false ; break ; } } if ( Tf ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { int age [ ] = { 5 , 15 , 10 } ; int candy [ ] = { 2 , 2 , 2 , 3 , 3 , 4 } ; int n = sizeof ( age ) / sizeof ( age [ 0 ] ) ; int k = sizeof ( candy ) / sizeof ( candy [ 0 ] ) ; check_distribution ( n , k , age , candy ) ; return 0 ; }