![]() |
VOOZH | about |
Given an array arr[] where each element represents the rating of a child, find the minimum number of candies required to distribute among all children under the following conditions:
Examples:
Input: arr[] = [1, 2, 3, 4, 5]
Output: 15
Explanation: According to the rule, if a childβs rating is greater than the neighbor, he must get more candy than the neighbor.
Child 0 β rating 1 β gets 1 candy
Child 1 β rating 2 β greater than 1 β gets 2 candies
Child 2 β rating 3 β greater than 2 β gets 3 candies
Child 3 β rating 4 β greater than 3 β gets 4 candies
Child 4 β rating 5 β greater than 4 β gets 5 candies
Total candies are 1 + 2 + 3 + 4 + 5 = 15.Input: arr[] = [9, 9, 9, 9]
Output: 4
Explanation: No child has a strictly greater rating than the neighbor. So, each child only needs the minimum 1 candy.
Table of Content
We need to ensure each student has more candies than both of their neighbors if their score is higher.
To handle the left neighbor, we traverse left β right: if a studentβs score is higher than the one on the left, give them more candies.
To handle the right neighbor, we traverse right β left: if a studentβs score is higher than the one on the right, give them more candies.
Finally, for each student we take the sum of maximum from both passes.
Why does taking the maximum work?
Every student must satisfy both neighbors:
But a student might need more candies to satisfy one side than the other. To keep the rule valid in both directions at once, we give them the maximum of the two counts. This way, no student violates the rule with either neighbor, while still keeping the distribution minimal.
15
The key idea is that every valid candy distribution forms slopes of increasing and decreasing ratings.
On an increasing slope, each child must get 1 more candy than the previous one. This ensures all local rising conditions are satisfied.
On a decreasing slope, the same logic applies in reverse, so each child gets 1 more than the next.
At a peak, both conditions apply. By subtracting the smaller overlap, we avoid double-counting but still guarantee the peak has more candies than both neighbors.
Steps to solve the problem:
15