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
Candy Distribution ProblemChildren with Ratings:10213Child 0Child 1Child 2Child 3Child 4Required Candies:21212Constraints: Each child gets ≥1 candy, higher rated children get more than neighborsMinimum Total Candies: 2 + 1 + 2 + 1 + 2 = 8🍭 Children 0,2,4 have higher ratings than neighbors → get more candies
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
Asked in
Google 45 Amazon 38 Facebook 32 Apple 28
285.0K Views
Medium Frequency
~35 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen