1)所有人分1个candy
2)从左往右查看,若满足左规则,令 candy[i] =candy[i - 1] + 1
3)从右往左查看,若满足右规则,令 candy[j] =Math.max(candy[j + 1] + 1,candy[j]),取最大值是为了在满足右规则的时候不破坏左规则
bash
class Solution {
public int candy(int[] ratings) {
if(ratings.length==0) return 0;
int candy[] =new int[ratings.length];
int total=0;
candy[0]=1;
//从左向右遍历数组使其满足左规则
for(int i=1;i<ratings.length;i++){
candy[i]=1;
if(ratings[i]>ratings[i-1]){
candy[i]=candy[i-1]+1;
}
}
//从右向左遍历数组使其满足左规则
for(int i=ratings.length-2;i>=0;i--){
if(ratings[i]>ratings[i+1]){
candy[i]=Math.max(candy[i+1]+1,candy[i]);
}
}
//遍历获得糖果总数
for(int i=0;i<ratings.length;i++){
total+=candy[i];
}
return total;
}
}