# leetcode135. Candy

## 题目要求

``````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?``````

• 每个孩子至少有一颗糖
• 有更高评估值的孩子应当比两侧孩子得到的糖更多

## 思路和代码

`[1,2,3,4,1, , , , , ]`

`[1,2,3,4,1,2,1, , , ]`

`[1,2,3,4,1,2,2,1, , ]`

`[1,2,3,4,1,2,3,2,1, ]`

`[1,2,3,4,1,2,3,2,1,2]`

• 当后一个孩子比前一个孩子评分高时，直接在前一个孩子糖果数量基础上加1
• 当后一个孩子比前一个孩子评分低时

• 前一个孩子糖果数量大于1，则该孩子糖果数量为1
• 前一个孩子糖果数量为1，则该孩子糖果数量为1，并且将前面相应孩子的糖果数量加1
• 当后一个孩子和前一个孩子评分一样多，则该孩子糖果数量为1

``````    public int candy(int[] ratings) {
int count = 1;
int summitIndex = 0;
int summitCandy = 1;
int prevCandy = 1;
for(int i = 1 ; i<ratings.length ; i++){
if(ratings[i] > ratings[i-1]){
prevCandy++;
count += prevCandy;
summitIndex = i;
summitCandy = prevCandy;
}else if(ratings[i] < ratings[i-1]){
if(prevCandy == 1){
count += (i - summitIndex) + (i-summitIndex >= summitCandy ? 1 : 0);
}else{
prevCandy = 1;
count += prevCandy;
}
}else{
prevCandy = 1;
count += prevCandy;
summitIndex = i;
summitCandy = prevCandy;
}
}
return count;
}``````

265 人关注
247 篇文章