## 一、题目

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give?

N 个小孩站成一列。每个小孩有一个评级。

• 每个小孩至少得到一颗糖果。
• 评级越高的小孩可以比他相邻的两个小孩得到更多的糖果。

## 三、解题代码

``````public class Solution {
public int candy(int[] ratings) {
if(ratings == null || ratings.length == 0) {
return 0;
}

int[] count = new int[ratings.length];
Arrays.fill(count, 1);
int sum = 0;
for(int i = 1; i < ratings.length; i++) {
if(ratings[i] > ratings[i - 1]) {
count[i] = count[i - 1] + 1;
}
}

for(int i = ratings.length - 1; i >= 1; i--) {
sum += count[i];
if(ratings[i - 1] > ratings[i] && count[i - 1] <= count[i]) {  // second round has two conditions
count[i-1] = count[i] + 1;
}
}
sum += count;
return sum;
}
}
``````
Copyright © ruheng.com 2017 all right reserved，powered by Gitbook该文件修订时间： 2018-05-12 01:48:13