135. Candy
来源:互联网 发布:js 页面就绪函数 编辑:程序博客网 时间:2024/06/04 10:31
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?
求需要发的最小的糖果数。要求每个小孩都要有一颗,并且等级高的小孩要比旁边的多。这里要注意相邻的同等级的糖果数可以不一样。对给出的等级vector,正向遍历一次,反向遍历一次就能得到答案。纪念第一次100%。。。
代码:
class Solution{public:int candy(vector<int>& ratings){int res=0,n=ratings.size();vector<int>nums(n,1);for(int i=1;i<n;i++){if(ratings[i]>ratings[i-1]){nums[i]=nums[i-1]+1;}}for(int i=n-2;i>=0;i--){if(ratings[i]>ratings[i+1]){nums[i]=max(nums[i+1]+1,nums[i]);}}for(int i=0;i<n;i++){res+=nums[i];}return res;}};
0 0
- 135.Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 135. Candy
- 十分钟搞定Openresty安装
- 摄影技巧
- okhttp的get访问(加header)
- 理解一般指针和指向指针的指针
- 守护线程
- 135. Candy
- a标签中target="_blank"属性存在的缺陷
- 进程和线程的区别
- html中元素定位
- 简单实现hibernate-validator拓展
- android的Tab实现布局
- Android中Scroller类的了解
- jquery简易轮播图
- [LeetCode] Kth Largest Element in an Array (找出数组的第k大的元素)