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
def check_distribution ( n , k , age , candy ) : NEW_LINE INDENT mxage = max ( age ) + 1 NEW_LINE mxcandy = max ( candy ) + 1 NEW_LINE fr1 = [ 0 ] * mxage NEW_LINE fr2 = [ 0 ] * mxcandy NEW_LINE for j in range ( n ) : NEW_LINE INDENT fr1 [ age [ j ] ] += 1 NEW_LINE DEDENT for j in range ( k ) : NEW_LINE INDENT fr2 [ candy [ j ] ] += 1 NEW_LINE DEDENT k = 0 NEW_LINE Tf = True NEW_LINE for j in range ( mxage ) : NEW_LINE INDENT if ( fr1 [ j ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT flag = False NEW_LINE while ( k < mxcandy ) : NEW_LINE INDENT if ( fr1 [ j ] <= fr2 [ k ] ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT k += 1 NEW_LINE DEDENT k = k + 1 NEW_LINE if ( flag == False ) : NEW_LINE INDENT Tf = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( Tf ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT age = [ 5 , 15 , 10 ] NEW_LINE candy = [ 2 , 2 , 2 , 3 , 3 , 4 ] NEW_LINE n = len ( age ) NEW_LINE k = len ( candy ) NEW_LINE check_distribution ( n , k , age , candy ) NEW_LINE