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?
Java:
http://blog.csdn.net/linhuanmars/article/details/21424783
CodeGanker的解法好简练 最后没看懂..
public class Solution {
public int candy(int[] ratings) {
if(ratings.length==0||ratings==null) return 0;
int[] nums=new int[ratings.length];
nums[0]=1;
for(int i=1;i<ratings.length;i++)
{
if(ratings[i]>ratings[i-1])
{
nums[i]=nums[i-1]+1;
}
else{
nums[i]=1;
}
}
int res=nums[ratings.length-1];
for(int i=ratings.length-2;i>=0;i--)
{
int cur=1;
if(ratings[i]>ratings[i+1])
{
cur=nums[i+1]+1;
}
res=res+Math.max(nums[i],cur);//confused,why they want max here
nums[i]=cur;
}
return res;
}
}
这个解法更清晰:
http://rleetcode.blogspot.com/2014/01/candy-java.html
public class Solution {
public int candy(int[] ratings) {
if(ratings.length==0||ratings==null) return 0;
int[] nums=new int[ratings.length];
for(int i=0;i<nums.length;i++)
{
nums[i]=1;
}
for(int i=1;i<ratings.length;i++)
{
if(ratings[i]>ratings[i-1])
{
nums[i]=nums[i-1]+1;
}
}
//int res=nums[ratings.length-1];
for(int i=ratings.length-2;i>=0;i--)
{
int cur=1;
if(ratings[i]>ratings[i+1]&&nums[i]<=nums[i+1])
{
nums[i]=nums[i+1]+1;
}
}
int total=0;
for(int i=0;i<nums.length;i++)
{
total+=nums[i];
}
return total;
}
}