LeetCode135—Candy
来源:互联网 发布:mac 查找文件路径 编辑:程序博客网 时间:2024/05/29 02:43
原题
原题链接
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?
分析
N个小孩,每个小孩有一个等级,且每个小孩的等级如果比他临近的小孩高,那么他将得到更多的糖果。
求最少需要多少糖果才能满足上述要求,且每个小孩至少一个糖果。
模拟这个过程,可能会想到:
求最少需要多少糖果,先每个人分配一个,再根据等级依次加一个糖果。
但上述思路是会有问题的,那就是对于小孩
因此两次循环,一次从左到右,一次从右往左。
代码
class Solution {public: int candy( vector <int>& ratings) { int N= ratings.size(); vector<int>count(N,1); for(int i=1;i<ratings.size();i++) { if(ratings[i]>ratings[i-1]) count[i]=count[i-1]+1; } for(int i=N-1;i>0;i--) { if(ratings[i]<ratings[i-1]) { count[i-1]=max(count[i]+1,count[i-1]); } } return accumulate(count.begin(),count.end(),0); }};
1 0
- Leetcode135——Candy
- LeetCode135—Candy
- Leetcode135(Candy)
- leetcode135~Candy
- LeetCode135 Candy
- Leetcode135 candy
- Leetcode135: Simplify Path
- LeetCode——Candy
- *candy——leetcode
- LeetCode——Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- iOS--错误集锦--svn提交出错 an error occurred and the operation could not be completed
- leetCode_Minimum Window Substring
- html img Src base64 图片显示
- Common motion planning algorithms 常用机器人运动规划算法
- 输出逆序数
- LeetCode135—Candy
- 自己挖的坑,跪着也填完
- 关于扫描二维码拒绝获取摄像头权限导致的错误解决方法
- ceilometer+gnocchi+influxdb
- AsyncTask加载之图片下载(2)
- 扫盲+备份
- boost的编译、使用
- 解决IllegalStateException: Can not perform this action after onSaveInstanceState
- Android中RelativeLayout和LinearLayout性能分析