Problem
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?
Example
Given ratings = [1, 2]
, return 3
.
Given ratings = [1, 1, 1]
, return 3
.
Given ratings = [1, 2, 2]
, return 4
. ([1,2,1]).
Note
保证rating
高的小朋友拿到的糖果更多,我们建立一个分糖果数组A
。小朋友不吃糖果,考试拿A
也是可以的。
首先,分析边界条件:如果没有小朋友,或者只有一个小朋友,分别对应没有糖果,和有一个糖果。
然后我们用两个for
循环来更新分糖果数组A
。
排排坐,吃果果。先往右,再往左。右边高,多一个。左边高,吃得多。
这样,糖果数组可能就变成了类似于[0, 1, 0, 1, 2, 3, 0, 2, 1, 0]
,小朋友们一定看出来了,这个不是真正的糖果数,而是根据考试级别ratings
给高分小朋友的bonus。
好啦,每个小朋友至少要有一个糖果呢。
bonus总和加上小朋友总数n
,就是要准备糖果的总数啦。
Solution
public class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
if (n < 2) return n;
int[] A = new int[n];
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i-1]) A[i] = A[i-1]+1;
}
for (int i = n-2; i >= 0; i--) {
if (ratings[i] > ratings[i+1]) A[i] = Math.max(A[i], A[i+1]+1);
}
int res = n;
for (int a: A) res += a;
return res;
}
}