#include <iostream> #include <vector> #include <algorithm> using namespace std; Question of candy/* There are N children standing in a line.
Each child is assigned a rating value. You are are giving candies to this children subjected to the following Requirements:each child must have at least one candy
.
Children with a higher rating to more candies than their.
* * Problem-solving ideas: traverse both sides, first of all a piece of sugar, the first time from left to right, if the current point than the former one more than a point. This ensures that the requirements are met in one direction.
The second time from right to left, if about two points, left above the right, but the left of the number of sweets not more than the right, then the left candy number equals the right candy number +1, which ensures that the other direction to meet the requirements.
Finally, add up the number of sweets in each position.
* * int Candycount (vector<int>&rating) {int res = 0;
Total children int n = rating.size ();
Candy Set vector<int> Candy (n, 1);
Iterate from left to right for (int i = 0;i < n-1;i++) {if (rating[i + 1] > Rating[i]) candy[i + 1] = Candy[i] + 1; //From right to left for (int i = n-1;i > 0;i--) {if (rating[i-1] > Rating[i] && candy[i-1] <
= Candy[i]) candy[i-1] = Candy[i] + 1;
}Cumulative result for (auto A:candy) {res + A;
return res;
///test function int main () {vector<int> rating{1,3,2,1,4,5,2};
cout << Candycount (rating) << Endl;
return 0;
}