LeetCode 135 : Candy
来源:互联网 发布:古代西亚北非文明知乎 编辑:程序博客网 时间:2024/06/05 02:13
[LeetCode 135 : Candy](LeetCode 135 : Candy)
题目大意
- Description
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) { int size = ratings.size(); vector<int> num(size,1); int counter =0; for(int i=0;i<size;i++){ if(ratings[i]>ratings[i-1]){ num[i] = num[i-1]+1; } } for(int i=size-1;i>=0;i--){ if(ratings[i]<ratings[i-1] && num[i]>=num[i-1]){ num[i-1]=num[i]+1; } counter+=num[i]; } return counter; }
分析
定义一个整型数组num,长度与ratings数组相同,初始值均为1,。ratings数组先从前向后,每个元素与前一个相比,如果ratings值大则对应的num值等于前一个的加1,然后从后向前依次比,如果前一个元素的ratings值大于后一个的,同时它的num值不大于后一个的num值,其num值等于后一个的num值加一。
阅读全文
0 0
- [Leetcode 135, Hard] Candy
- LeetCode: Candy [135]
- [leetcode 135] Candy
- LeetCode(135) Candy
- [LeetCode 135]Candy
- LeetCode 135 Candy
- leetcode || 135、Candy
- [leetcode-135]Candy(java)
- leetcode 135: Candy
- leetCode #135 Candy
- 【LeetCode-135】Candy
- Leetcode (135) Candy
- LeetCode(135)Candy
- Leetcode. 135 Candy(Hard)
- LeetCode 135 Candy
- LeetCode 135 : Candy
- leetcode 135 —— Candy
- LeetCode 135:candy 题解 Python
- java后台实现发送邮件的功能
- 解码为yuv
- HDU 4734 F(x) 数位DP
- 121. Best Time to Buy and Sell Stock
- 【自定义View】1.View的滑动
- LeetCode 135 : Candy
- CentOS 6.5 下 CDH 5.2.1 集群安装
- 关于使用file上传图片获取图片绝对路径
- HTML初学习
- H5~居中、盒模型、float(浮动)、position(定位)等问题
- BZOJ 4241 历史研究
- iOS 宏定义~RGB(颜色)
- MySQL数据表中的字段操作
- js的三大核心组成部分