题目:
There are N children standing ina line. Each child is assigned a rating value.
You are giving candies to these childrensubjected to the following requirements:
Each child musthave at least one candy.
Children with ahigher rating get more candies than their neighbors.
What is the minimum candies you must give?
思路:
用一个数组 candy[n],表示第i 个小孩所应该发的最少糖果数。
数组 ratings[n] 表示每个小孩的评分。
1. 从左到右扫描一遍,
candy[i] = 1, if ratings[i] <= ratings[i-1] ;
candy[i] = candy[i-1] + 1, if ratings[i] > ratings[i-1]
2. 从右到左扫描一遍,
candy[i] = candy[i], if ratings[i] <= ratings[i+1] ;
candy[i] = max(candy[i], candy[i+1] + 1), if ratings[i] > ratings[i+1]
解法:
动态规划
复杂度:
时间:时间 O(n),空间 O(n)
实现:
public int candy(int[] ratings){
intsize=ratings.length;
if(size<=1)return size;
int[]nums=new int[size];
for(inti=0;i<size;i++){
nums[i]=1;
}
for(intj=1;j<size;j++){
if(ratings[j]>ratings[j-1])nums[j]=nums[j-1]+1;
}
for(intm=size-1;m>0;m--){
if(ratings[m-1]>ratings[m]){
nums[m-1]=Math.max(nums[m]+1,nums[m-1]);
}
}
intresult=0;
for(intn=0;n<size;n++){
result+=nums[n];
}
returnresult;
}