LeetCode 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?
有N个孩子站在一条线。分配给每个孩子一个评级的价值。
你把糖果给这些孩子受到以下需求:
每个孩子必须至少有一个糖果。
评级较高的孩子得到更多的糖果比他们的邻居。
什么是你必须给的最低糖果吗?
以上内容是用有道翻译进行翻译
解题思路:------------------------------------------
每个小孩先发一块糖,然后从左向右进行遍历,如果arr[i]>arr[i-1],就在前一个人的糖的数目的基础上加1;
最后从右往左遍历,加上所有的糖(从右往左遍历是考虑到权值为:7 5 8 9 6 4 12)的情况
import java.util.*;
public class Solution {
public int candy(int[] ratings) {
if(ratings==null || ratings.length==0) {
return 0;
}
int[] count = new int[ratings.length];
//每个孩子初始都有一个糖果
Arrays.fill(count,1);
int sum = 0;
for(int i=1;i<ratings.length;i++) {
if(ratings[i]>ratings[i-1]) {
count[i] = count[i-1]+1;
}
}
for(int i=ratings.length-1;i>0;i--) {
sum+=count[i];
if(ratings[i]<ratings[i-1] && count[i]>=count[i-1]) {
count[i-1] = count[i]+1;
}
}
sum+=count[0];
return sum;
}
}