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块糖果。
采取2次扫描,从前向后,再从后向前。 当然也可以反过来。
从前向后扫描过程中,如果后者rating高于前者,则在前者的糖果数量基础上+1,为后者的糖果数。
此趟扫描结束后,ratings递增的孩子分得糖果数,将满足要求。
再反向扫描,将使ratings递减也满足题目要求。 第二趟 所要注意的事, 一个小孩的糖果数不能减少,只能增加。 否则第一趟的成果就不保。
可以将ratings数组想象成,由多个山峰组成。 即由低到高,再由高到低。 只是每个峰平缓陡峭成度不一样。
在leetcode上实际执行时间为44ms。
class Solution {
public:
int candy(vector<int>& ratings) {
if (ratings.empty()) return 0;
vector<int> candy(ratings.size(), 1);
for (int i=ratings.size()-2; i>=0; i--) {
if (ratings[i] > ratings[i+1])
candy[i] = candy[i+1]+1;
}
int ans = candy[0];
for (int i=1; i<ratings.size(); i++) {
if (ratings[i] > ratings[i-1])
candy[i] = max(candy[i], candy[i-1]+1);
ans += candy[i];
}
return ans;
}
};