Chocolate Distribution Problem | Set 2 | FUnction to prlet 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 ; Given array ; Size of the given array
function minChocolates ( A , N ) { let B = new Array ( N ) . fill ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) { B [ i ] = 1 ; } for ( let i = 1 ; i < N ; i ++ ) { if ( A [ i ] > A [ i - 1 ] ) B [ i ] = B [ i - 1 ] + 1 ; else B [ i ] = 1 ; } for ( let i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] > A [ i + 1 ] ) B [ i ] = Math . max ( B [ i + 1 ] + 1 , B [ i ] ) ; else B [ i ] = Math . max ( B [ i ] , 1 ) ; } let sum = 0 ; for ( let i = 0 ; i < N ; i ++ ) { sum += B [ i ] ; } document . write ( sum + " " ) ; } let A = [ 23 , 14 , 15 , 14 , 56 , 29 , 14 ] ; let N = A . length ; minChocolates ( A , N ) ;