Original question stamp me
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?
class Solution {public: int candy(vector<int> &ratings) { std::vector<int> num(ratings.size(), 1); int inc = 2; for (int i = 1; i < ratings.size(); ++i) { if (ratings.at(i) > ratings.at(i - 1)) { num.at(i) = std::max(inc++, num.at(i)); } else { inc = 2; } } inc = 2; for (int i = ratings.size() - 2; i >= 0; --i) { if (ratings.at(i) > ratings.at(i + 1)) { num.at(i) = std::max(inc++, num.at(i)); } else { inc = 2; } } int res = std::accumulate(num.begin(), num.end(), 0); return res; }};
Step 1 first initialize each element of the secondary array to 1, because each element must be at least 1
Step 2: scan from left to right. If a number is larger than its left adjacent number, the number at the corresponding position of the num array will be incrementally assigned from 2 (note that equal values do not need to be added ), otherwise, the increment value is initially 2.
After traversing, it can be satisfied: If a number in the original array is greater than its left adjacent number, the corresponding auxiliary array must also be greater than its left adjacent number.
If ratings [I]> = ratings [I + 1], ratings [I + 1] must be 1
Step3. traverse from right to left, similar to step 2
Actually, in step 2, num. at (I) must be equal to INC ++, because before num. at (I) is changed, it is initially set to 1.
Why must we add the comparison between INC and num. at (I) in step 3? Because the size condition of the array after Step 2 must be met.
The original array is: 1 --> 2 --> 5 --> 4 --> 3 --> 2 --> after 1step2, The num array is: 1 --> 2 --> 3 --> 1 --> 1 --> 1 --> 1step3 traversing from right to left to idx = 2: 1 --> 2 --> (3 or 5) --> 4 --> 3 --> 2 --> 1
Idx = 2. It must be greater than the left adjacent number, which is greater than the right adjacent number, so the max operation is available.
Leetcode: Candy. Each number is larger than the adjacent number.