题目大意:
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,从右边开始往左边遍历。如果左边孩子的分数比右边孩子高,则左边孩子比右边孩子多一个糖果。同时,对该孩子,选取上次从左向右遍历时,孩子的糖果和现在更新过得孩子糖果中,糖果较多的作为结果。
代码如下:
class Solution {
public:
int candy(vector<int> &ratings) {
int length = ratings.size();
if(length == 0){
return 0;
}
int i;
vector<int> candy1;
candy1.push_back(1);
for(i=1;i<length;i++){
if(ratings[i] > ratings[i-1]){
candy1.push_back(*(candy1.end()-1) + 1);
}
else{
candy1.push_back(1);
}
}
int m = 0;
for(i=length-2;i>=0;i--){
if(ratings[i] > ratings[i+1]){
m = candy1[i+1] + 1;
if(m > candy1[i]){
candy1[i] = m;
}
}
}
int sum = 0;
for(i=0;i<length;i++){
sum += candy1[i];
}
return sum;
}
};