The question is to distribute candies to N children.Each child has a rating. Distribution should be such that each child have at least one candy and children with higher rating gets more candies than their neighbors. Find minimum number of candies for such distribution.
Approach:
iterate each child.
if (rating of curr child < rating of next child)
add to total and increase candy
else if (rating of curr child equal to rating of next child)
we can bring down candy for next child to 1
else if ( rating of curr child > rating of next child)
{ // if child ratings are {4 3 2 5} then
//optimal is {3 2 1 2}
//the detailed code is below
}
The detailed code is :
int n = A.size();
int count = 0;
int step = 1;
int i = 0;
bool run = true;
while(run){
if(i+1 ==n){
count+=step;
run = false;
}
else if(A[i+1] > A[i]){
count+=step;
step++;
i+=1;;
}else if(A[i+1] == A[i]){
count+=step;
step = 1;
i+=1;
}else {
int j = i;
while(A[i+1] < A[i]&& (i+1)<n){
i+=1;
}
int x = i-j;
step = max(step,x+1);
count+=step;
count+=((x*(x+1))/2);
step = 2;
if(i==n-1)
run = false;
i+=1;
}
}
return count;
The code doesn't produce expected output. Due to huge size of test case, I cannot determine cause of error. Can someone provide sample test case where it breaks?
The failed test case is attached in below link. The first number denotes size of array. Breaking test case