Chocolate Distribution Problem | Set 2 | Function to print minimum number of candies required ; Distribute 1 chocolate to each ; Traverse from left to right ; Traverse from right to left ; Initialize sum ; Find total sum ; Return sum ; Driver Code ; Given array ; Size of the given array
def minChocolates ( A , N ) : NEW_LINE INDENT B = [ 1 for i in range ( N ) ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( A [ i ] > A [ i - 1 ] ) : NEW_LINE INDENT B [ i ] = B [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT B [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] > A [ i + 1 ] ) : NEW_LINE INDENT B [ i ] = max ( B [ i + 1 ] + 1 , B [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT B [ i ] = max ( B [ i ] , 1 ) NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += B [ i ] NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 23 , 14 , 15 , 14 , 56 , 29 , 14 ] NEW_LINE N = len ( A ) NEW_LINE minChocolates ( A , N ) NEW_LINE DEDENT