6 Candy_Leetcode
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 3 2 7 5 4 2
第一眼我们肯定会想到让一些波谷(1, 3, 2)的糖果个数为1, 然后依次从这些值往左和往右扩张填充。如果只能想到模拟的方法,那这题基本没法做。
这里值得强调的是,一般情况下,面试要考察的都不会是简单的模拟。
除了与左边和右边的邻居比较,我们还能怎么理解这个问题呢?
如果从定序的角度来看,我们可以从左到右和从右到左遍历这个序列,对于每一个位置,它需要的糖果数量与它从某个方向看过来是第几个连续增长的数有关。并且是从左与从右看的结果中取较大。
有了这种“定序”的思想,找到解答的方法也就很简单了。
值得注意的是,在从一个方向往另一个方向扫描的过程中,由于连续相等的数值之间是不做比较的,所以相等的数可以只发一个糖果,作为下一个递增序列的开始。
Code:
class Solution {
public:
int candy(vector<int> &ratings) {
int n = ratings.size();
if(n == 0) return 0;
int sum = 0;
vector<int> left(n, 1);
vector<int> right(n, 1);
for(int i = 1; i < n; i++)
{
if(ratings[i] > ratings[i-1]) left[i] = left[i-1] + 1;
else left[i] = 1; // first error, when equal, no camparison, so the candy could start from 1
}
for(int j = n-2; j >= 0; j--)
{
if(ratings[j] > ratings[j+1]) right[j] = right[j+1] + 1;
else right[j] = 1;
}
for(int i = 0; i < n; i++) sum += max(left[i], right[i]);
return sum;
}
};
6 Candy_Leetcode的更多相关文章
随机推荐
- unity小地图技术方案总结
技术方案 一:从顶视图获取实时小地图(优点实现快容易对地图进行放大缩小操作而且地图,缺点是不好对地图做出修改,只能在顶部加个另外的相机层来遮盖) 1.创建Redertexture并改名为smallma ...
- ip地址库 新浪,淘宝
原文连接地址:http://www.9958.pw/post/city_ip function getAddressFromIp($ip){ $urlTaobao = 'http://ip.taoba ...
- Java优先队列
按照Java api的说法: java.util.PriorityQueue.PriorityQueue() Creates a PriorityQueue with the default init ...
- tomcat启动的了,但是加载项目失败
解决方法: 1.tomcat启动是好的,也有可能找不到tomcat的dll,所以,检查一下myeclipse所使用的tomcat的解压目录是不是有空格,有空格的话,重新解压到一个新目录,千万不要有空格 ...
- angularjs 新窗口打开
原文链接:angularjs 中state.go 跳转并且打开新的浏览器窗口 业务需要,需要点击打开一个新窗口,并且是点击事件触发的打开新窗口: $scope.lookLook =function(d ...
- 如何查看/统计当前AD域控制器的活动用户?
最近公司想知道某台AD域控制器上当前连接了多少活动用户? 此前个人只知道以下不是非常完善且统计起来比较麻烦的方法: 方法1:查看共享会话数.(不完全准确) 方法2:查看当前的DNS记录.(这种方法统计 ...
- 【IOS】将一组包含中文的数据按照#ABC...Z✿分组
上一篇文章[IOS]模仿windowsphone列表索引控件YFMetroListBox里面 我们一步步的实现了WindowsPhone风格的索引. 但是有没有发现,如果你要实现按照字母排序,你还得自 ...
- 【DS】About Stack
栈 一言以蔽之,就是后进的先出(LIFO). C语言实现代码: #include<stdio.h> #include<stdlib.h> typedef struct Stac ...
- scrapy 学习笔记
1.scrapy 配合 selenium.phantomJS 抓取动态页面, 单纯的selemium 加 Firefox浏览器就可以抓取动态页面了, 但开启窗口太耗资源,而且一般服务器的linux 没 ...
- 【bzoj1672】[USACO2005 Dec]Cleaning Shifts 清理牛棚
题目描述 Farmer John's cows, pampered since birth, have reached new heights of fastidiousness. They now ...