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;
}
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;
}
相关文章推荐
- 【LeetCode笔记】Candy
- 4.19 leetcode -19 candy
- LeetCode135 Candy
- 【leetcode】Candy
- (LeetCode 135) Candy N个孩子站成一排,给每个人设定一个权重
- [leetcode] Candy Java
- leetcode-Candy
- [LeetCode] Candy
- LeetCode | Candy
- 【LeetCode-135】Candy
- LeetCode——Candy
- LeetCode 笔记25 Candy (艰难的调试)
- LeetCode 135 Candy
- leetCode_Candy
- LeetCode: Candy 解题报告
- LeetCode--candy
- leetcode:Candy
- Leetcode. 135 Candy(Hard)
- LeetCode Candy
- Leetcode Candy