Problem:
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?
题意是有N个小孩站成一排,然后你手上有无限的糖果,然后每个小孩都有一个概率值,然后我们需要给这些小孩糖果,其中要满足两个条件:
1.每个小孩都要有糖果;
2.比起隔壁的小孩,有个更高概率值的小孩能得到更多的糖果。
现在要求你最少要给多少个糖果。
其实题目不是很难,主要是要对小孩左右邻居进行一个比较,要满足rate值大的,candy数要大。如果小的话分1个,因为要求最小,所以大的概念是多1个糖果就行。所以我们先从左到右循环一遍,和左边小孩进行比较,大于的话就等于前一个小孩得到的糖果值++,否则等于1。这样就得到了一个candy数组。然后再从右到左遍历一遍,这样就能和右边小孩比较,如果大的话,就从candy数组中该小孩对应的值和右边小孩糖果值+1选一个最大值(因为要同时满足左右小孩的比较条件),如果是小的话,直接等于1。最后把所有值加起来就是结果了。
Code:(LeetCode运行26ms)
class Solution {
public:
int candy(vector<int>& ratings) {
int size = ratings.size();
vector<int> each_candy(size);
for (int i = 1, now_candy = 1; i < size; i++) {
if (ratings[i] > ratings[i - 1]) {
each_candy[i] = now_candy++;
} else {
now_candy = 1;
}
}
for (int i = size - 2, now_candy = 1; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
each_candy[i] = max(each_candy[i], now_candy++);
} else {
now_candy = 1;
}
}
int sum = size;
for (int i = 0; i < size; i++) {
sum += each_candy[i];
}
return sum;
}
};