Candy
来源:互联网 发布:交大知行大厦电话 编辑:程序博客网 时间:2024/06/16 16:45
题目描述:
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?
分析:这是一道非常经典的算法题,对每一个人而言,至少有一颗糖,所以数组初始化为一,然后进行由前到后,由后到前两次遍历,来维护最小数需要的合法糖果数即可。
代码如下:
int candy(vector<int>& ratings) { vector<int> ans(ratings.size(),1); for (int i = 1; i < ratings.size(); i++) { if(ratings[i]>ratings[i-1]) ans[i]=ans[i-1]+1; } for (int i= ratings.size()-1; i>0 ; i--) { if(ratings[i-1]>ratings[i]) ans[i-1]=max(ans[i]+1,ans[i-1]); } int result=0; for (int i = 0; i < ratings.size(); i++) { result+=ans[i]; } return result; }
阅读全文
0 0
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- candy
- Candy
- Candy
- Candy
- Candy
- Spring3.X学习笔记4-Spring容器高级主题
- 企业网站首页设计常见的6种布局方式
- 方法区和常量池
- 使用BeautifulSoup对糗事百科热门进行爬取
- 自动抛出异常的应用
- Candy
- oracle中where条件后用in这样子查询后变慢
- mysql出现错误“ Every derived table must have its own alias”
- LVM逻辑卷管理 练习
- C++ 最小化到托盘
- MYSQL问题:Access denied for user 'root'@'localhost' (using password:YES)
- codevs 1014 装箱问题
- hdu 1847 巴什博奕
- 大数据资源整理 ---持续更新