Candy
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?
解题思路:
1、从左到右扫描,如果右边比左边分数高,右边在左边糖果数基础上+1,否则糖果数为1
2、从右边到左扫描,如果左边分数比右边大,且左边糖果树不小于或等于右边糖果数,那么左边糖果数在右边糖果数基础上+1
3、最后求糖果数总和
public class Solution {
public int candy(int[] ratings) {
if(ratings.length==1)
return 1;
int[] candy=new int[ratings.length];
candy[0]=1;//
for(int i=1;i<ratings.length;i++){
if(ratings[i-1]<ratings[i]){//如果右边比左边分数大,就糖果数加1
candy[i]=candy[i-1]+1;
}else{
candy[i]=1;//否则糖果数为1
}
}
for(int i=ratings.length-2;i>=0;i--){
if(ratings[i]>ratings[i+1]&&candy[i]<=candy[i+1]){
candy[i]=candy[i+1]+1;
}
}
int sum=0;
for(int i=0;i<ratings.length;i++){
sum+=candy[i];
}
return sum;
}
}