您的位置:首页 > 其它

Leetcode: Candy

2013-10-02 12:12 295 查看
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?

public class Solution {
public int candy(int[] ratings) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int len = ratings.length;
if(len == 0)
return 0;
int minSum = len;
// Each child must have at least one candy. Better start this way.
// I got bugs when start with minSum = 0
int curCandy = 0;
int[] candy = new int[ratings.length];
for(int i = 1; i < len; i++){
if(ratings[i - 1] < ratings[i])
++curCandy;
else
curCandy = 0;
candy[i] = curCandy;
}
curCandy = 0;
for(int i = len - 2; i >= 0;i--){
if(ratings[i] > ratings[i + 1])
++curCandy;
else
curCandy = 0;
minSum += Math.max(candy[i], curCandy);
}
minSum += candy[len - 1];
return minSum;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: