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的更多相关文章

随机推荐

  1. 【转】MySQL性能优化的最佳21条经验

    文章转自: http://blog.csdn.net/waferleo/article/details/7179009 今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关 ...

  2. GMOLO平板——如何安装新系统

    1.首先,此款平板采用intel处理器Z3735F,不支持Win7,XP,经过测试,Win8可以在此类笔记本及平板上运行,并非只能安装最新的Win10系统. 2.下载Win8 32位系统作为预备(GH ...

  3. laravel5 安装笔记

    1.环境更新 apt-get update apt-get install php5-cli apt-get install curl 2. Composer安装 curl -sS https://g ...

  4. Python - 类与对象的方法

    类与对象的方法

  5. nmq消息队列解析

    消息中间件NMQ 1.What is nmq? nmq = new message queue; 一个通用消息队列系统 为在线服务设计 什么是消息队列?问什么需要?有哪些功能? 消息队列的本质:1.多 ...

  6. Python 简易聊天机器人

    聊天机器人 | |-----MySql | |---module--"逻辑运算层" | | | |---ciku--"与词库交互" | | | |---dict ...

  7. struts1和struts2的区别

    1. 在Action实现类方面的对比:Struts 1要求Action类继承一个抽象基类:Struts 1的一个具体问题是使用抽象类编程而不是接口.Struts 2 Action类可以实现一个Acti ...

  8. Android Studio Error:CreateProcess error=216

    Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you' ...

  9. redis的一些操作

    public class WnsRedisFactory { private static Cache pool = null; private static JedisConnectionFacto ...

  10. BZOJ2802——[Poi2012]Warehouse Store

    1.题目巨短,自己看看吧 2.分析:这道题,想了半天dp还是想不到,最后看题解发现是个贪心的思想,我们维护一个堆,如果这个人不能加入就把他和堆上最大的进行比较,然后搞搞就行了 #include < ...