Distribution of candies according to ages of students | 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
function check_distribution ( n , k , age , candy ) { let mxage = age [ 0 ] ; for ( let i = 0 ; i < age . length ; i ++ ) { if ( mxage < age [ i ] ) { mxage = age [ i ] ; } } let mxcandy = candy [ 0 ] ; for ( let i = 0 ; i < candy . length ; i ++ ) { if ( mxcandy < candy [ i ] ) { mxcandy = candy [ i ] ; } } let fr1 = new Array ( mxage + 1 ) ; fr1 . fill ( 0 ) ; let fr2 = new Array ( mxcandy + 1 ) ; fr2 . fill ( 0 ) ; for ( let j = 0 ; j < n ; j ++ ) { fr1 [ age [ j ] ] += 1 ; } for ( let j = 0 ; j < k ; j ++ ) { fr2 [ candy [ j ] ] += 1 ; } k = 0 ; let Tf = true ; for ( let j = 0 ; j < mxage ; j ++ ) { if ( fr1 [ j ] == 0 ) { continue ; } let 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 ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } let age = [ 5 , 15 , 10 ] ; let candy = [ 2 , 2 , 2 , 3 , 3 , 4 ] ; let n = age . length ; let k = candy . length ; check_distribution ( n , k , age , candy ) ;