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。然后倒序遍历一个,做相同的操作,就可以满足题目要求。
代码:
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; } };
相关文章推荐
- Candy - Leetcode
- LeetCode: Candy
- 6 Candy_Leetcode
- LeetCode--candy
- LeetCode Candy Greedy
- 【Leetcode】Candy
- [LeetCode]Candy
- [LeetCode] Candy (分糖果),时间复杂度O(n),空间复杂度为O(1),且只需遍历一次的实现
- Leetcode 动态规划 Candy
- [Leetcode] Candy
- [LeetCode] Candy
- leetCode---Candy
- LeetCode:Candy
- [leetcode]Candy @ Python
- leetcode -day9 Candy & Gas Station & Binary Tree Maximum Path Sum
- [LeetCode] Candy, Solution
- [LeetCode][JavaScript]Candy
- [Leetcode] Candy (Java)
- LeetCode:Candy
- Candy -- LeetCode