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?
解题思路:用了比较麻烦的方法,遍历两遍数组,第一遍对于确保右边比左边的人拿到的糖果符合条件;第二遍遍历来修正左边对于右边的情况;
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int candy(vector<int> &ratings) {
int ChildrenNum = ratings.size();
vector<int>CandyVector(ChildrenNum, 1);
for (int i = 0; i < ChildrenNum-1;++i){
if (ratings[i] < ratings[i + 1])
CandyVector[i + 1] = CandyVector[i] + 1;
}
for (int i = ChildrenNum-1; i >0; --i){
if (ratings[i] < ratings[i - 1]&&CandyVector[i]>=CandyVector[i-1])
CandyVector[i - 1] = CandyVector[i] + 1;
}
return accumulate(CandyVector.begin(), CandyVector.end(), 0);
}