Chocolate Distribution Problem | Set 2 | Function to return minimum number of chocolates ; decreasing sequence ; add the chocolates received by that person ; end point of decreasing sequence ; val = 1 ; reset value at that index ; increasing sequence ; flat sequence ; add value of chocolates at position n - 1 ; helper function to get sum of decreasing sequence ; value obtained from decreasing sequence also the count of values in the sequence ; assigning max of values obtained from increasing and decreasing sequences ; sum of count - 1 values & peak value sum of natural numbers : ( n * ( n + 1 ) ) / 2 ; Driver code
function minChocolates ( a , n ) { let i = 0 , j = 0 ; let res = 0 , val = 1 ; while ( j < n - 1 ) { if ( a [ j ] > a [ j + 1 ] ) { j += 1 ; continue ; } if ( i == j ) res += val ; else { res += get_sum ( val , i , j ) ; } if ( a [ j ] < a [ j + 1 ] ) val += 1 ; else val = 1 ; j += 1 ; i = j ; } if ( i == j ) res += val ; else res += get_sum ( val , i , j ) ; return res ; } function get_sum ( peak , start , end ) { let count = end - start + 1 ; peak = ( peak > count ) ? peak : count ; let s = peak + ( ( ( count - 1 ) * count ) >> 1 ) ; return s ; } let a = [ 5 , 5 , 4 , 3 , 2 , 1 ] ; let n = a . length ; document . write ( " " + minChocolates ( a , n ) ) ;