LeetCode||candy
来源:互联网 发布:明星p图软件 编辑:程序博客网 时间:2024/05/17 03:30
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?
class Solution {
public:int candy(vector<int> &ratings) {
/*
遍历两边,首先每个人得一块糖,第一遍从左到右,若当前点比前一个点高就比前者多一块。
这样保证了在一个方向上满足了要求。第二遍从右往左,若左右两点,左侧高于右侧,但
左侧的糖果数不多于右侧,则左侧糖果数等于右侧糖果数+1,这就保证了另一个方向上满足要求
*/
int n=ratings.size();
vector<int> child(n);
for(int i=0;i<n;i++)
child[i]=1;
int i=0;
for(i=1;i<n;i++)
{
if(ratings[i]>ratings[i-1])
child[i]=child[i-1]+1;
}
for(i=n-2;i>=0;i--)
{
if(ratings[i]>ratings[i+1]&&child[i]<=child[i+1])
child[i]=child[i+1]+1;
}
return accumulate(child.begin(),child.end(),0);
}
};
阅读全文
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
- Android开发小技巧系列(二)
- ActionBar详解
- 关于ffmpeg工具的使用总结
- 关于Java中的注解
- GlusterFS企业级功能之EC纠删码
- LeetCode||candy
- JS中盒模型相关
- 有头单链表排序
- 跳转传值startActivityForResult +回调
- 洛谷 P3225 [HNOI2012]矿场搭建
- 1318:n%m
- 牛客网-考研上机-成绩排序
- 机器学习之PCA
- mysql存储过程查询结果循环遍历 判断 赋值 游标等基本操作