您的位置:首页 > 其它

leetcode_Candy

2015-05-15 13:51 351 查看
描述:

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.新建一个数组arr,给每个元素赋值为1,即每个孩子的糖果至少为1个

2.从左至右,假设rating[i]<rating[i+1],则arr[i+1]=arr[i]+1;

3.从右至左,若rating[i]<rating[i-1],则比较arr[i-1]=max(arr[i-1],arr[i]+1)

4.从左至右,统计糖果的数量即可。

代码:

public int candy(int[] ratings) {
if(ratings==null)
return 0;
if(ratings.length<=1)
return ratings.length;
int count=0;
int len=ratings.length;
int candyNum[]=new int[len];
Arrays.fill(candyNum, 1);
for(int i=1;i<len;i++)
{
if(ratings[i]>ratings[i-1])
candyNum[i]=candyNum[i-1]+1;
}
for(int i=len-1;i>=1;i--)
{
if(ratings[i]<ratings[i-1])
{
if(candyNum[i-1]<candyNum[i]+1)
candyNum[i-1]=candyNum[i]+1;
}

}
for(int i=0;i<len;i++)
count+=candyNum[i];
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: