LeetCode 135. Candy
来源:互联网 发布:淘宝中学生书包女韩版 编辑:程序博客网 时间:2024/05/21 22:27
题目要求:
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?
每个小朋友至少分到一块糖,且分数比周围小朋友高的小朋友分到的糖更多。求最少需要给多少块糖。
看到这道题我一开始的想法是将一个数组按递增递减划分:如[1 2 3 4 3 2 1],这个数组可分为两段:1~4上升,4~1下降。用cnt记录while循环中上升/下降个数,记录值自加且跳出while循环后cnt置1。后来运行的时候[1 2 4 4 3]没有通过。原因是这个想法只考虑了从左到右的顺序,而实际上a[3]的值是由a[4]确定的,所以需要遍历两次:从左到右一次,从右到左一次。用数组记录两次遍历中的值并取两次中的较大值。
C++代码如下:
class Solution {public: int candy(vector<int>& ratings) { int n = ratings.size(); vector<int> nums(n, 1); for(int i=1; i<n; i++) { if(ratings[i-1]<ratings[i]) nums[i] = nums[i-1]+1; } for(int i=n-1; i>0; i--) { if(ratings[i-1]>ratings[i]) nums[i-1] = max(nums[i]+1, nums[i-1]); } int sum = 0; for(int i=0; i<n; i++) sum += nums[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
- 判断蓝牙打开关闭状态+wifi打开关闭状态
- 3
- Dl4j-fit(DataSetIterator iterator)源码阅读(二)
- 自定义View绘制五星红旗
- linux sed命令用法举例
- LeetCode 135. Candy
- maven 搭建多war包聚合项目
- 编译和链接
- 自顶向下 逐步求精 完成任务
- Linux初级入门命令篇(2)
- stl知识整理-应付CCF考试
- set算法 (交集,并集,差集,对称差集)
- Java使用反射处理注解
- 人工智能是否会超越人类?