The problem statement is here https://www.interviewstreet.com/challenges/dashboard/#problem/4fe12e4cbb829
You are distributing candy among children. All the children sit in a line and each of
them has a rating score according to his or her usual performance. Each child gets
at least 1 piece. Children get jealous of their immediate neighbors, so if two
children sit next to each other then the one with the higher rating must get
more candies. You wants to save money, so minimize the total number of candies.
Input: A file with the children's ratings, 1 per line.
And my code is working for small input sizes but for a very large input its either not giving any output ( on the interview.com console) or deviating from the answer by a small amount on my system.
What cold be the error in my code?
#include <stdio.h>
int main()
{
int i, j, n, rating[100000], candy[1000000], total = 0;
scanf("%d", &n);
for (i=0 ; i < n; i++)
{
scanf("%d",&rating[i]);
candy[i] = 1;
}
for (i=0 ; i < n+1 ; i++)
{
for (j=1 ; j < n-1; j++)
{
if( rating[j-1] < rating[j] )
{
if ( candy[j-1] >= candy[j] )
candy[j]++;
}
if( rating[j+1] < rating[j] )
{
if ( candy[j+1] >= candy[j] )
candy[j]++;
}
}
}
for (i=0 ; i < n ; i++)
total = total + candy[i];
printf("%d",total);
return 0;
}
You might be running into one of the translation limits of your implementation with the automatic arrays
ratingandcandy. Try placing them at file scope, i.e. outside ofmain. Then they have static storage duration. Most systems allow much larger static objects than automatic objects.