# A simple solution

• ``````  int candy(vector<int> &ratings)
{
int size=ratings.size();
if(size<=1)
return size;
vector<int> num(size,1);
for (int i = 1; i < size; i++)
{
if(ratings[i]>ratings[i-1])
num[i]=num[i-1]+1;
}
for (int i= size-1; i>0 ; i--)
{
if(ratings[i-1]>ratings[i])
num[i-1]=max(num[i]+1,num[i-1]);
}
int result=0;
for (int i = 0; i < size; i++)
{
result+=num[i];
// cout<<num[i]<<" ";
}
return result;
}``````

• Good solution, same as mine in Java.

—————————————————————

The upper was my first comment, and gained many -1.
So I post my java code as the second comment.
This is my third comment, to explain .

As some guys want to see my code, see below please.

``````public int candy(int[] ratings) {

int len = ratings.length;
int[] candy = new int[len];

candy[0] =1;
for (int i = 1; i < len; ++i) {
if (ratings[i] > ratings[i-1]) {
candy[i] = candy[i-1] + 1;
} else {
candy[i] = 1;
}
}

int total = candy[len-1];
for (int i = len - 2; i >= 0; --i) {
if (ratings[i] > ratings[i+1] && candy[i] <= candy[i+1]) {
candy[i] = candy[i+1] + 1;
}
total += candy[i];
}
}``````

• Why In second scan we are traverse from the end, Why not starting from start.

• It's due to the computation dependency. In the second scan, num[i-1]=max(num[i]+1,num[i-1]). In other words, num[i-1] depends on num[i]. So num[i] must be computed before num[i-1].

• really easy to understand. good solution.

• very simple, I understand, thanks for sharing your code~

• Incredibly simple code! I am really interested in your thouhgt process of how to come up with such a nice solution :-)

• Any one can prove this solution is correct?

• U can U show your JAVA code, no can no bb.

• Many thanks for your solution.
if input array is `1,3,3,3,2`, candy is `1,2,1,2,1` rather than '1,2,2,2,1'.

• good! I was thinking how to deal with equal rates. when one children's rate equal with both neighbors, give him one candy would be enough.

• 23333333333333

• I don't know what you said before so that got so many downs..... But the code is really nice. help you to cancel a -1...

• Yes, the idea and code is quite good and easy to understand. I will help you cancel a -1 and add a +1.

• Sharing good solution should be inspired. So UP + 1.

• Great idea !

• Really interested in what you said in your post. Why you got so many votes down?

• I don't know what happened, but I think there must be some reason why so many people vote down on you, so I follow them -1

• Let's start taking guess of what he could have posted.
"Here's my JAVA code" .. and then he forgot to post the code

• Exciting solution and I helped you vote it up...

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.