15. Candy π¬
β GFG solution for minimum candies to distribute to children given ratings. Peak-valley & two-pass solutions with linear time guarantees and multi-language code. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[] where each element represents a child's rating. You need to distribute candies to these children following these rules:
Each child must receive at least one candy.
Children with a higher rating than their neighbors must receive more candies than those neighbors.
Your task is to find the minimum number of candies needed to satisfy these conditions.
π Examples
Example 1
Input: arr[] = [1, 0, 2]
Output: 5
Explanation: Child at index 1 has the lowest rating, so gets 1 candy.
Child at index 0 has rating higher than index 1, so gets 2 candies.
Child at index 2 has rating higher than index 1, so gets 2 candies.
Total candies = 2 + 1 + 2 = 5.Example 2
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$0 \le \text{arr}[i] \le 10^9$
β
My Approach
The optimal approach uses the Peak-Valley technique to minimize candy distribution in a single pass with constant space:
Peak-Valley Single Pass Algorithm
Initialize Variables:
Start with
total = n(each child gets at least 1 candy).Use pointer
istarting at index 1 to traverse the array.
Handle Equal Ratings:
When
arr[i] == arr[i-1], no extra candies needed - just move to next child.
Identify Peaks (Ascending Sequence):
While ratings increase (
arr[i] > arr[i-1]), we're climbing a peak.Each step up requires one more candy than the previous child.
Track the peak height and add candies accordingly.
Identify Valleys (Descending Sequence):
While ratings decrease (
arr[i] < arr[i-1]), we're descending into a valley.Each step down requires one more candy than the next child (going backwards).
Track the valley depth and add candies accordingly.
Optimize Overlap:
At the transition point between peak and valley, one child is counted in both.
Subtract the minimum of peak and valley heights to avoid double-counting.
The taller sequence already satisfies the constraint for the transition child.
Continue Until End:
Repeat the process for all peaks and valleys until reaching the end of the array.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We traverse the array once, processing each element exactly once during peak and valley identification.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables like
total,i,peak, andvalley, regardless of input size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated