leetCode---Candy
来源:互联网 发布:facebook 程序员薪资 编辑:程序博客网 时间:2024/05/29 20:00
一. 题目: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个孩子站在一条线上。每个孩子被分配一个评分值。你给这些孩子的糖果受到以下要求:每个孩子必须至少有一个糖果。具有较高评级的儿童比邻居获得更多的糖果。你必须给予的最少糖果是什么? 思路分析:这是一个贪心算法的应用,先从左到右扫描一遍,使得右边比左边得分高的小朋友糖果数比左边多。再从右到左扫描一遍,使得左边比右边得分高的小朋友糖果数比右边多。代码如下:
class Solution { public: int candy(vector<int>& ratings) { int len = ratings.size(), res = 0, i; if(len>0){ vector<int> number(len,0); number[0] = 1; for(i=1; i<len;++i) number[i] = ratings[i]>ratings[i-1]?number[i-1]+1:1; for(i=len-2, res = number[len-1]; i>=0;--i){ if( (ratings[i]>ratings[i+1]) && number[i]<(number[i+1]+1) ) number[i] = number[i+1]+1; res += number[i]; } } return res; } };
阅读全文
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
- iOS开发之MAC上SVN的使用
- 2_python连接MariaDB错误
- LeetCode试题之““给定一个正整数A,找到最小的正整数B,它的每一个数字的乘法等于A。””
- day09 数组形参、递归、全局/局部变量、static
- Activity的启动模式:FLAG_ACTIVITY_CLEAR_TOP和FLAG_ACTIVITY_REORDER_TO_FRONT
- leetCode---Candy
- 十分钟搞定上传本地项目到github
- 1_urllib2.HTTPError HTTP Error 500 INTERNAL SERVER ERROR
- treefrog之视图 Otama模版系统
- JWT token心得与使用实例
- Memcached-基础
- rtmp协议简单解析以及用其发送h264的flv文件——史上最详细
- 深度学习DBN深度置信网络
- switch语句