Candy
来源:互联网 发布:json 特殊字符大括号 编辑:程序博客网 时间:2024/05/18 04:19
Thereare N children standing in a line. Each child is assigned arating value.
You are giving candiesto 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 minimumcandies you must give?
思路:跟trapwater的思路比较像,就是每个item上的取值取决于左右两边,所以需要左右扫两遍。从左往右扫的时候如果item左边的比他大就置为最低1,如果比他小就+1,右边同理。每个item的值为左右的最大值。
Ref:http://www.cnblogs.com/springfor/p/3877120.html
class Solution {public: int candy(vector<int> &ratings) { if (ratings.size() == 0) { return 0; } int size = ratings.size(); vector<int> left(size, 0); vector<int> right(size, 0); left[0] = 1; for (int i = 1; i < size; i++) { if (ratings[i] > ratings[i - 1]) { left[i] = left[i - 1] + 1; } else { left[i] = 1; } } right[size - 1] = 1; for (int i = size - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1]) { right[i] = right[i + 1] + 1; } else { right[i] = 1; } } int result = 0; for (int i = 0; i < size; i++) { result += max(right[i], left[i]); } return result; }};
0 0
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- Candy
- candy
- Candy
- Candy
- Candy
- Candy
- MySQL慢查询
- FaustCplus
- 【转】openfire+spark+smack实现即时通讯
- 工作日记
- SAPI的学习 安装SAPI扩展包
- Candy
- swift singleton class
- js 判断是否为空
- Http请求状态及jquery ajax请求异常处理
- SAP NCO 连接.NET平台的MSSQL(流星程序集之十一)
- Surrounded Regions
- 事务控制代码示例
- javascript学习总结
- Distinct Subsequences