您的位置:首页 > 其它

LEETCODE: Candy

2015-01-06 22:33 381 查看
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.从左往右扫描,如果右边比左边大,那么右边的是左边的 + 1。

2.从右往左扫描,如果左边比右边大,那么左边的是右边的 + 1 和自己原有的值中那个比较大的数。

3.把1,2扫描所得的结果相加,记住每个孩子都要给糖果,所以各个数还要+ 1。

class Solution {
public:
int candy(vector<int> &ratings) {
if(ratings.size() == 0) return 0;
vector<int> candies(ratings.size());
for(int ii = 1; ii < ratings.size(); ii ++) {
if(ratings[ii] > ratings[ii - 1]) {
candies[ii] = candies[ii - 1] + 1;
}
}
for(int ii = ratings.size() - 1; ii >= 0; ii --) {
if(ratings[ii] < ratings[ii - 1]) {
candies[ii - 1] = max(candies[ii] + 1, candies[ii - 1]);
}
}
int total = 0;
for(int ii = 0; ii < candies.size(); ii ++) {
total += candies[ii] + 1;
}
return total;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息