您的位置:首页 > 其它

LeetCode-Candy

2017-09-18 20:58 344 查看
1. Candy(Hard)

Description[/i]

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?

Analysis[/i]

分析题意,每个Children至少有一颗Candy,我们可以初始化每个Children的Candy的数量为1,然后比较每个Children的和他前后的Children的rating,如果他的rating高于前后的Children的,则他的Candy数量必须至少比其他两个Children的更大值大1。但是前后一起比较并不好实现,我们可以先正序遍历ratings,如果当前Children的rating大于前一个Children的rating,则他的Candy数比前一个大1。然后倒序遍历一个,做相同的操作,就可以满足题目要求。

代码:

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