Candy -- leetcode
来源:互联网 发布:mac 管理员账户没有了 编辑:程序博客网 时间:2024/06/12 09:21
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块糖果。
采取2次扫描,从前向后,再从后向前。 当然也可以反过来。
从前向后扫描过程中,如果后者rating高于前者,则在前者的糖果数量基础上+1,为后者的糖果数。
此趟扫描结束后,ratings递增的孩子分得糖果数,将满足要求。
再反向扫描,将使ratings递减也满足题目要求。 第二趟 所要注意的事, 一个小孩的糖果数不能减少,只能增加。 否则第一趟的成果就不保。
可以将ratings数组想象成,由多个山峰组成。 即由低到高,再由高到低。 只是每个峰平缓陡峭成度不一样。
在leetcode上实际执行时间为44ms。
class Solution {public: int candy(vector<int>& ratings) { if (ratings.empty()) return 0; vector<int> candy(ratings.size(), 1); for (int i=ratings.size()-2; i>=0; i--) { if (ratings[i] > ratings[i+1]) candy[i] = candy[i+1]+1; } int ans = candy[0]; for (int i=1; i<ratings.size(); i++) { if (ratings[i] > ratings[i-1]) candy[i] = max(candy[i], candy[i-1]+1); ans += candy[i]; } return ans; }};
0 0
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- CVS使用命令
- 第十三周项目1(3)-动物这样叫
- java获取当前某个时间点
- 搜索引擎——匹配方式
- 情景菜单ContextMenu的创建
- Candy -- leetcode
- CSDN学院系统停站维护
- GRE数学中的应试技巧之数量部分的三种题型
- iOS 数据存储 - 03SQLite编程
- 作为一个新人,怎样学习嵌入式Linux?(转自韦东山老师)
- Linux socket编程案例
- 为什么将能被4整除但不能被100整除和能被400整除的年份设为闰年
- 仿QQ微信发表说说点击编辑框输入法上边出现表情按钮,点击可选择表情
- 简单Dos命令