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:ui
- 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?spa
举个例子,1 3 2 7 5 4 2blog
第一眼咱们确定会想到让一些波谷(1, 3, 2)的糖果个数为1, 而后依次从这些值往左和往右扩张填充。若是只能想到模拟的方法,那这题基本无法作。rem
这里值得强调的是,通常状况下,面试要考察的都不会是简单的模拟。get
除了与左边和右边的邻居比较,咱们还能怎么理解这个问题呢?it
若是从定序的角度来看,咱们能够从左到右和从右到左遍历这个序列,对于每个位置,它须要的糖果数量与它从某个方向看过来是第几个连续增加的数有关。而且是从左与从右看的结果中取较大。io
有了这种“定序”的思想,找到解答的方法也就很简单了。ast
值得注意的是,在从一个方向往另外一个方向扫描的过程当中,因为连续相等的数值之间是不作比较的,因此相等的数能够只发一个糖果,做为下一个递增序列的开始。class
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; } };