题目描述
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.
- 每一个小孩至少一个糖果;
- 等级值高的小孩要比等级值低小孩分配的糖果多;
解题思路
思路很简单,首先给所有小孩分配一个糖果,满足条件一;其次,顺序扫描一遍,找到顺序的递增数列,分配糖果;第三逆序扫描一遍,找到逆序的递增数列,分配糖果,满足条件二。over!
代码
/**
* 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.
* @param ratings
* @return
*/
public static int candy(int[] ratings) {
int length = ratings.length;
int[] candies = new int[length];
int result = 0;
Arrays.fill(candies, 1);
//顺序扫一遍,找出递增序列并加糖果
for (int i = 1; i < length; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
result += candies[length - 1];
//逆序扫一遍,找出递增序列并加糖果
for (int i = length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
}
result += candies[i];
}
return result;
}