Candy Distribution
Master this topic with zero to advance depth.
Candy Distribution
Each child has a rating. You must give candies such that:
- Every child gets at least 1 candy.
- Children with a higher rating get more candies than their neighbors.
Return the minimum total candies.
Visual Representation
Ratings: [1, 0, 2]
Pass 1 (L->R):
[1, 0, 2] -> [1, 1, 2] (fixes child at index 2 rank > index 1)
Pass 2 (R->L):
[1, 0, 2] -> [2, 1, 2] (fixes child at index 0 rank > index 1)
Total: 5Examples
Candies: [2, 1, 2]. Total = 5.
Level I: Brute Force (Iterative Satisfaction)
Intuition
Repeatedly scan the ratings and candies. If a child has a higher rating than a neighbor but doesn't have more candies, give them one more. Repeat until no more changes are needed.
Thought Process
- Initialize
candieswith 1 for all. - In a loop, keep track if any changes were made (
changed = false). - For each child
i:- If
ratings[i] > ratings[i-1]andcandies[i] <= candies[i-1], setcandies[i] = candies[i-1] + 1, changed = true. - Same for
i+1.
- If
- Stop when
changedis false.
Detailed Dry Run
ratings=[1,2,3], initial=[1,1,1] Pass 1: [1,2,1] (i=1), [1,2,3] (i=2). changed=true. Pass 2: No changes. Total=6.
Level II: Peak and Valley (Single Pass)
Intuition
We can think of the ratings as a sequence of mountains (peaks) and valleys. The number of candies increases as we climb a mountain from a valley, and decreases as we descend. The 'peak' child gets the maximum needed from both sides.
Thought Process
- Use variables
up,down, andpeakto track the current mountain slopes. - If rating increases,
up++,down=0,peak=up. Candies +=up + 1. - If rating decreases,
down++,up=0. Candies +=down. - If
down > peak, we need to add one extra candy to the peak to keep it higher than the descending slope.
Pattern: Slope Analysis
Detailed Dry Run
ratings = [1, 2, 1]
- i=1 (up): up=1, peak=1, candies = 1 + (1+1) = 3.
- i=2 (down): down=1, up=0. down <= peak (1 <= 1). candies = 3 + 1 = 4. Sum = 4? Wait, [1, 2, 1] should be [1, 2, 1] -> 4. Correct.
Level III: Optimal Greedy (Two Independent Passes)
Intuition
A child must satisfy two conditions: candies[i] > candies[i-1] if ratings[i] > ratings[i-1], and candies[i] > candies[i+1] if ratings[i] > ratings[i+1]. We can solve these separately.
Thought Process
- Start all children with 1 candy.
- L-to-R: If
rating[i] > rating[i-1], setcandies[i] = candies[i-1] + 1. - R-to-L: If
rating[i] > rating[i+1], setcandies[i] = max(candies[i], candies[i+1] + 1).
Pattern: Constraint Satisfaction in Multiple Passes
Detailed Dry Run
ratings = [1, 2, 8, 7, 3, 4, 1] L->R: [1, 2, 3, 1, 1, 2, 1] R->L: [1, 2, 3, 2, 1, 2, 1] Result: 12
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.