Minimum number of candies required to distribute among children based on given conditions | Function to count the minimum number of candies that is to be distributed ; Stores total count of candies ; Stores the amount of candies allocated to a student ; If the value of N is 1 ; Traverse the array arr [ ] ; If arr [ i + 1 ] is greater than arr [ i ] and ans [ i + 1 ] is at most ans [ i ] ; Assign ans [ i ] + 1 to ans [ i + 1 ] ; Iterate until i is atleast 0 ; If arr [ i ] is greater than arr [ i + 1 ] and ans [ i ] is at most ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; If arr [ i ] is equals arr [ i + 1 ] and ans [ i ] is less than ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; Increment the sum by ans [ i ] ; Return the resultant sum ; Driver Code
def countCandies ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = [ 1 ] * n NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i + 1 ] > arr [ i ] and ans [ i + 1 ] <= ans [ i ] ) : NEW_LINE INDENT ans [ i + 1 ] = ans [ i ] + 1 NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] and ans [ i ] <= ans [ i + 1 ] ) : NEW_LINE INDENT ans [ i ] = ans [ i + 1 ] + 1 NEW_LINE DEDENT elif ( arr [ i ] == arr [ i + 1 ] and ans [ i ] < ans [ i + 1 ] ) : NEW_LINE INDENT ans [ i ] = ans [ i + 1 ] + 1 NEW_LINE DEDENT sum += ans [ i ] NEW_LINE DEDENT sum += ans [ n - 1 ] NEW_LINE return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countCandies ( arr , N ) ) NEW_LINE DEDENT