?方法:贪心
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1);
//从前往后遍历,若当前评分大于前一个评分,多分发一个糖果
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
//从后往前遍历,若当前评分大于后一个评分,
//取当前分发的糖果与后一个孩子分发糖果+1的最大值,
//从而保证既比左边分发的糖果多,也比右边分发的糖果多
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
return Arrays.stream(candies).sum();
}
}
|