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主从复制、半同步复制和主主复制概述

    http://www.cnblogs.com/zping/p/5275531.html

  2. excel工具类

    excel工具类 import com.iport.framework.util.ValidateUtil; import org.apache.commons.lang3.StringUtils; ...

  3. juery学习总结(一)——juery选择器

    juery在工作中经常使用,遇到不会的问题往往百度一下,事后就忘.使用到现在也感觉不到有什么提高,为了每天进步一点点,从今天起抽时间记录下对juery的学习. 学习之前,首先要了解什么是网页元素,网页 ...

  4. Android中Context的理解及使用(二)——Application的用途和生命周期

    实现数据共享功能: 多个Activity里面,可以使用Application来实现数据的共享,因为对于同一个应用程序来说,Application是唯一的. 1.实现全局共享的数据App.java继承自 ...

  5. 现代软件工程作业 github使用

    Github使用 版本库的创建与同步 第一步:创建远程版本库并同步到本地 创建远程版本库 在地址栏输入www.github.com 并sign in 进入到个人主页,如下图示: 创建远程版本库:点击N ...

  6. laravel5 安装笔记

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

  7. ZOJ Problem Set - 3329(概率DP)

    One Person Game Time Limit: 1 Second      Memory Limit: 32768 KB      Special Judge There is a very ...

  8. jquery easyui datagrid翻页后再查询始终从第一页开始

    在查询之前将datagrid的属性pageNumber重新设置为1 var opts = grid.datagrid('options'); opts.pageNumber = 1; easyui d ...

  9. Webview和Html

    参考http://blog.csdn.net/chenzheng_java/article/details/6260872 <html><header> <title&g ...

  10. android 选择图片或拍照时旋转了90度问题

    由于前面的博文中忽略了点内容,所以在这里补上,下面内容就是解决拍照或者选择图片显示的时候图片旋转了90度或者其他度数问题,以便照片可以正面显示:具体如下: 首先直接看上面博文下的拍完照或者选完图后处理 ...