Chocolate Distribution Problem | Set 2 | C ++ program for the above approach ; 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
#include <iostream> NEW_LINE using namespace std ; void minChocolates ( int A [ ] , int N ) { int B [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = 1 ; } for ( int i = 1 ; i < N ; i ++ ) { if ( A [ i ] > A [ i - 1 ] ) B [ i ] = B [ i - 1 ] + 1 ; else B [ i ] = 1 ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] > A [ i + 1 ] ) B [ i ] = max ( B [ i + 1 ] + 1 , B [ i ] ) ; else B [ i ] = max ( B [ i ] , 1 ) ; } int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += B [ i ] ; } cout << sum << " STRNEWLINE " ; } int main ( ) { int A [ ] = { 23 , 14 , 15 , 14 , 56 , 29 , 14 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; minChocolates ( A , N ) ; }