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?
[分析] 开一个数组num[], num[i]表示位置i处的孩子分到的candy数。先从前往后扫描,确保ratings[i] > ratings[i - 1]时,num[i] > num[i - 1],然后从后往前扫描,确保ratings[i] > ratings[i + 1]时,num[i] > num[i + 1],两遍扫描后就能满足题意了,计算需要的candy总数。
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?
[分析] 开一个数组num[], num[i]表示位置i处的孩子分到的candy数。先从前往后扫描,确保ratings[i] > ratings[i - 1]时,num[i] > num[i - 1],然后从后往前扫描,确保ratings[i] > ratings[i + 1]时,num[i] > num[i + 1],两遍扫描后就能满足题意了,计算需要的candy总数。
public class Solution {
public int candy(int[] ratings) {
int N = ratings.length;
int[] num = new int[N];
for (int i = 1; i < N; i++) {
if (ratings[i] > ratings[i - 1])
num[i] = num[i - 1] + 1;
}
for (int i = N - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && (num[i] <= num[i + 1]))
num[i] = num[i + 1] + 1;
}
int sum = N;
for (int i = 0; i < N; i++) {
sum += num[i];
}
return sum;
}
}
本文详细阐述了如何通过两次扫描数组来确保每个孩子都至少得到一颗糖果,且糖果数量根据其评分与邻居进行比较,从而实现最小糖果分配的算法过程。
432

被折叠的 条评论
为什么被折叠?



