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 Problem INPUT Children in a line: Rating: 1 idx: 0 Rating: 0 idx: 1 Rating: 2 idx: 2 Rating Graph (Peak/Valley): 1 0 2 valley peak ratings = [1, 0, 2] ALGORITHM STEPS 1 Initialize Give 1 candy to each child candies = [1, 1, 1] 2 Left to Right Pass If rating[i] > rating[i-1]: candy[i] = candy[i-1] + 1 candies = [1, 1, 2] 3 Right to Left Pass If rating[i] > rating[i+1]: candy[i] = max(candy[i], candy[i+1] + 1) candies = [2, 1, 2] 4 Sum All Candies Total = 2 + 1 + 2 = 5 2 1 2 candies FINAL RESULT Candy Distribution: Child 0 2 candies Child 1 1 candy Child 2 2 candies Verification: Rating 1 > 0: OK (2 > 1) Rating 2 > 0: OK (2 > 1) Output: 5 Key Insight: The greedy approach detects peaks and valleys in ratings. By making two passes (left-to-right and right-to-left), we ensure each child gets more candies than lower-rated neighbors. The valley (rating 0) gets minimum candies, while neighbors with higher ratings get progressively more. This guarantees the minimum total distribution. TutorialsPoint - Candy | One Pass Greedy with Peak/Valley Detection
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