Leetcode 135. Candy
来源:互联网 发布:2015各省人口普查数据 编辑:程序博客网 时间:2024/06/11 00:31
题目:
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?
思路:
这题本身可以用贪心法来做,我们用candy[n]表示每个孩子的糖果数,遍历过程中,如果孩子i+1的rate大于孩子i 的rate,那么当前最好的选择自然是:给孩子i+1的糖果数=给孩子i的糖果数+1
如果孩子i+1的rate小于等于孩子i 的rate咋整?这个时候就不大好办了,因为我们不知道当前最好的选择是给孩子i+1多少糖果。
解决方法是:暂时不处理这种情况。等数组遍历完了,我们再一次从尾到头遍历数组,这回逆过来贪心,就可以处理之前略过的孩子。
最后累加candy[n]即得到最小糖果数。
代码:
class Solution {public: int candy(vector<int>& ratings) { int num = ratings.size(); vector<int> res(num, 1); for(int i = 1; i < num; ++ i){ if(ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1; } for(int i = num-1; i >0; --i){ if(ratings[i-1] > ratings[i]) res[i-1] = max(res[i]+1, res[i-1]); } int sum = 0; for(int i = 0; i < num; ++ i){ sum += res[i]; } return sum; }};
0 0
- [LeetCode]135.Candy
- 135. Candy Leetcode Python
- [Leetcode] 135. Candy
- [leetcode] 135.Candy
- [leetcode] 135. Candy
- leetcode 135. Candy
- leetcode 135. Candy
- [LeetCode]135. Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode.135. Candy
- LeetCode 135. Candy
- [leetcode] 【数组】 135. Candy
- LeetCode-135.Candy
- LeetCode 135. Candy
- Leetcode 135. Candy
- leetcode-135. Candy
- [LeetCode] 135. Candy
- 《活法》读后总结
- JDBC
- Java多线程Thread类和Runable接口的区别以及线程类详解
- JAVA 实现163发邮件错误意思
- 取代安卓!谷歌新移动操作系统曝光:UI超帅超简约
- Leetcode 135. Candy
- 【android】1、intent
- qt获取文件—超大图标
- IOC/DI详解
- ArcGIS知乎上有哪些干货可以推荐?(持续更新中)
- swift可选型
- js获取页面元素距离浏览器工作区顶端的距离
- Servlet HTTP 状态码
- JDBC