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
using System ; public class GFG { static void minChocolates ( int [ ] A , int N ) { int [ ] B = new int [ 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 ] = Math . Max ( B [ i + 1 ] + 1 , B [ i ] ) ; else B [ i ] = Math . Max ( B [ i ] , 1 ) ; } int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += B [ i ] ; } Console . Write ( sum + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] A = { 23 , 14 , 15 , 14 , 56 , 29 , 14 } ; int N = A . Length ; minChocolates ( A , N ) ; } }