1 题目
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?
2 思路
按照网上的思路,每个孩子至少有一个糖果,先从左到右遍历一遍,写出递增的糖果数,再从右到左遍历一遍完成递减的糖果数。这种大小与左右两边数据相关的问题,均可以采用这个思路。另外,有另一种空间复杂度O(1),时间复杂度O(n)的思路,可以参考http://www.cnblogs.com/felixfang/p/3620086.html。
3 代码
public int candy(int[] ratings) {
if(ratings == null || ratings.length == 0)
{
return 0;
}
int[] candyNums = new int[ratings.length];
candyNums[0] = 1; for(int i = 1; i < ratings.length; i++)
{
if(ratings[i] > ratings[i-1]) //如果第i个孩子比第i - 1孩子等级高,
{
candyNums[i] = candyNums[i-1]+1;
}
else //每人至少有一个糖果
{
candyNums[i] = 1;
}
} for(int i = ratings.length-2; i >= 0; i--)
{ if(ratings[i] > ratings[i + 1] && candyNums[i] <= candyNums[ i + 1]) //如果第i个孩子比第i + 1孩子等级高并且糖果比i+1糖果少
{
candyNums[i] = candyNums[i + 1] + 1;
}
} int total = 0;
for (int i = 0; i < candyNums.length; i++) {
total += candyNums[i];
} return total;
}