LeetCode 135. Candy
来源:互联网 发布:can数据帧的格式结构 编辑:程序博客网 时间:2024/06/05 21:58
135. Candy
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个孩子站成一排,给每个人设定一个权重。按照如下的规则分配糖果: (1)每个孩子至少分得一颗糖果 (2)权重较高的孩子,会比他的邻居获得更多的糖果问一共最少需要多少颗糖果?*//*思路:设每个孩子分到的糖果数组为res[N],初始值为1,因为每个人至少分到一颗糖1、与前面的邻居比较,如果ratings[i]>ratings[i-1],则res[i]=res[i-1]+1,然后向后遍历数组ratings2、与后面的邻居比较,如果ratings[i]>ratings[i+1]且res[i]-res[i+1]<1,则res[i]=res[i+1]+1,然后向前遍历数组ratings3、对res求和即为最少需要的糖果*/class Solution {public: int candy(vector<int>& ratings) { int sum = 0; vector<int>res(ratings.size(), 1); for(int i = 1; i < ratings.size(); i++){ if(ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1; } for(int i = ratings.size()-2; i >= 0; i--){ if(ratings[i] > ratings[i+1] && res[i] - res[i+1] < 1) res[i] = res[i+1] + 1; } for(int i = 0; i < res.size(); 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
- YTU.1317: 控制台表格
- IO其他流--处理流保留数据+引用数据类型
- PostgreSQL备份与恢复示例
- 【安全牛学习笔记】离线密码破解、离线密码破解-Hashcat
- Linux中的输入输出管理及vim的简单操作
- LeetCode 135. Candy
- 拷贝构造函数、赋值函数浅析
- SSH 无法启动的原因分析及解决方法
- 使用commons-beanutils-1.8.3.jar提供的BeanUtils类快速封装属性时,遇到的错误
- LeakCanary使用(Android试手)
- Android Studio之maven Central,JCenter
- 【 Codeforces Round #367 (Div. 2) D】 Vasiliy's Multiset (Trie 按数位建字典树)
- 选择排序(简单选择排序--改进的简单选择排序--堆排序)
- post提交参数有Date类型,总是返回400格式错误