您的位置:首页 > 其它

leetcode -- Candy

2013-10-03 10:39 225 查看
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?

[解题思路]

two pass scan, one pass from left to right, next pass from right to left

when find increment sequence, set candy by k, then increment k

something need to attention, the requirement of this problem is that only children with a higher rating need to get more

candies than their neighors, but if two child has the same rating, we do not need to give more candies

the time complexity is O(n), the space complexity is also O(n)

public class Solution {
public int candy(int[] ratings) {
int N = ratings.length;
if(N == 0){
return N;
}
int[] candy = new int
;
int sum = N;
for(int i = 0, k = 1; i < N; i++){
if(i - 1 >= 0 && ratings[i] > ratings[i - 1]){
candy[i] = Math.max(k ++, candy[i]);
} else {
k = 1;
}
}

for(int i = N - 1, k = 1; i >= 0; i--){
if(i + 1 < N && ratings[i] > ratings[i + 1]){
candy[i] = Math.max(k ++, candy[i]);
} else {
k = 1;
}
}

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