Candy - Problem
There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
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.
Return the minimum number of candies you need to have to distribute the candies to the children.
Input & Output
Example 1 — Basic Case
$
Input:
ratings = [1,0,2]
›
Output:
5
💡 Note:
Child 0: rating=1, gets 2 candies (higher than right neighbor). Child 1: rating=0, gets 1 candy. Child 2: rating=2, gets 2 candies (higher than left neighbor). Total: 2+1+2=5
Example 2 — All Same Rating
$
Input:
ratings = [1,2,2]
›
Output:
4
💡 Note:
Child 0: rating=1, gets 1 candy. Child 1: rating=2, gets 2 candies (higher than left). Child 2: rating=2, gets 1 candy (same as left, no constraint). Total: 1+2+1=4
Example 3 — Decreasing Sequence
$
Input:
ratings = [5,4,3,2,1]
›
Output:
15
💡 Note:
Decreasing sequence requires candies [5,4,3,2,1] to satisfy neighbor constraints. Each child must have more candies than the right neighbor. Total: 5+4+3+2+1=15
Constraints
- n == ratings.length
- 1 ≤ n ≤ 2 × 104
- -1000 ≤ ratings[i] ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Ratings
Children with their performance ratings
2
Apply Constraints
Higher rated children need more candies than neighbors
3
Minimum Candies
Calculate minimum total candies needed
Key Takeaway
🎯 Key Insight: Use two-pass greedy to handle left and right neighbor constraints optimally
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code