There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
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. Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
Constraints:
- n == ratings.length
- 1 <= n <= 2 * 104
- 0 <= ratings[i] <= 2 * 104
class Solution {
public int candy(int[] ratings) {
int len=ratings.length;
int [] candy=new int[len];
// 1. 初始化糖果的数量为1
for(int i=0;i<len;i++){
candy[i]=1;
}
// 2. 从前往后:如果第i个小孩的等级>前面i-1个小孩的等级,那么糖果数+1
for(int i=1;i<len;i++){
if(ratings[i]>ratings[i-1]){
candy[i]=candy[i-1]+1;
}
}
// 3. 从后往前: 如果第i个小孩的等级>后面i+1个小孩的等级且糖果数少,那么糖果数+1
for(int i=len-2;i>=0;i--){
if((ratings[i]>ratings[i+1])&&(candy[i]<=candy[i+1])){
candy[i]=candy[i+1]+1;
}
}
int num=0;
for(int i=0;i<len;i++){
num+=candy[i];
}
return num;
}
}
初始化所有小孩糖数目为1,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。该算法时间复杂度为O(N)。之所以两次扫描,即可达成要求,是因为:第一遍,保证了每一点比他左边candy更多(如果得分更高的话)。第二遍,保证每一点比他右边candy更多(如果得分更高的话),同时也会保证比他左边的candy更多,因为当前位置的candy只增不减。