题目
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?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
分析
这道题的意思是给排成一排的孩子发糖果,每个孩子都有级别,发糖果必须满足两个要求:
- 每个孩子至少一个糖果
- 级别比相邻孩子高的哪个孩子,得到的糖果也要比相邻孩子的多
解法
这道题难度虽然被leetcode标记为Hard,但是并不难解决。第一个要求容易满足,主要是需要满足第二个要求,我们通过简单的遍历就可以得到每个孩子所分得的糖果数了。
输入的数组可以划分为三种子数组:从左至右递增的数组、从右至左递增的数组以及级别数相同的子数组。
对于输入[0, 1, 2, 3, 4]
,易知所需的最小糖果数为15,每个孩子得到的糖果数为[1, 2, 3, 4, 5]
。输入的孩子级别从左至右递增,因此他们得到的糖果数自然也需要从左至右递增。输入从右至左递增的情况也类似。
如果输入的子数组中级别数相同,如[2, 2, 2]
,那中间那个孩子的糖果数为1(给中间孩子发满足条件的最少的糖果数),另外两个孩子的糖果数取决于他们邻居的级别和糖果数。
以从左至右为例,我们采取的遍历的思想为:当前孩子的级别如果比他左边孩子的级别高,而且他的糖果数不比左边孩子的多的话,就把他的糖果数设置为左边孩子的糖果数 + 1(分配满足条件的最少的糖果数)。
但显然一次遍历是不够的,我们需要分别从左边和右边开始进行两次遍历。在从左至右遍历时,糖果数一定小于等于左边孩子的糖果数,因为此时左边孩子的糖果数已经被更新了。
代码
class Solution {
public:
int candy(const vector<int>& ratings) {
vector<int> candy(ratings.size(), 1);
//从两边开始分别遍历一次
for (int i = 1; i < ratings.size(); ++i) {
if (ratings[i] > ratings[i - 1]) {
candy[i] = candy[i - 1] + 1;
}
}
for (int i = ratings.size() - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1] && candy[i] <= candy[i + 1]) {
candy[i] = candy[i + 1] + 1;
}
}
int sum = 0;
for (auto i : candy) sum += i;
return sum;
}
};
算法时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( n ) O(n) O(n)