Candy - Problem

Imagine you're a teacher distributing candy to n children standing in a line. Each child has been given a rating based on their performance, and you need to distribute candies fairly while minimizing the total number of candies used.

The Rules:

  • ๐Ÿฌ Every child must receive at least one candy
  • โญ If a child has a higher rating than their neighbor, they must receive more candies than that neighbor
  • ๐ŸŽฏ You want to use the minimum total number of candies possible

Input: An integer array ratings where ratings[i] is the rating of the i-th child.

Output: The minimum number of candies needed to satisfy all requirements.

Example: If ratings are [1,0,2], child 0 gets 2 candies, child 1 gets 1 candy, child 2 gets 2 candies, totaling 5 candies.

Input & Output

example_1.py โ€” Basic case
$ Input: ratings = [1,0,2]
โ€บ Output: 5
๐Ÿ’ก Note: Child 0 (rating 1) gets 2 candies (more than child 1 with rating 0). Child 1 (rating 0) gets 1 candy. Child 2 (rating 2) gets 2 candies (more than child 1). Total: 2 + 1 + 2 = 5.
example_2.py โ€” All same ratings
$ Input: ratings = [1,2,2]
โ€บ Output: 4
๐Ÿ’ก Note: Child 0 gets 1 candy. Child 1 (rating 2 > 1) gets 2 candies. Child 2 (rating 2, same as child 1) gets 1 candy. Total: 1 + 2 + 1 = 4.
example_3.py โ€” Single child
$ Input: ratings = [5]
โ€บ Output: 1
๐Ÿ’ก Note: Only one child, so they get the minimum 1 candy regardless of their rating.

Constraints

  • n == ratings.length
  • 1 โ‰ค n โ‰ค 2 ร— 104
  • 0 โ‰ค ratings[i] โ‰ค 2 ร— 104

Visualization

Tap to expand
The Teacher's Two-Pass StrategyStudents in line: ratings = [1, 0, 2, 3, 1]๐Ÿ‘ฆR:1๐Ÿ‘งR:0๐Ÿ‘ฆR:2๐Ÿ‘งR:3๐Ÿ‘ฆR:1Pass 1: Left โ†’ Right1122>0 so +133>2 so +11Pass 2: Right โ†’ Left1124max(3,2)=41Final: [1, 1, 2, 4, 1] = 9 candies total โœ…
Understanding the Visualization
1
Initial Setup
Give every student 1 candy as the base amount
2
Left-to-Right Walk
Walk from first to last student, giving extra candy when a student has higher rating than their left neighbor
3
Right-to-Left Walk
Walk from last to first student, ensuring students with higher ratings than right neighbors have enough candy
4
Optimal Distribution
The two-pass approach guarantees minimum total candies while satisfying all fairness constraints
Key Takeaway
๐ŸŽฏ Key Insight: By making two separate passes (left-to-right, then right-to-left), we can satisfy all neighbor constraints optimally without needing complex logic or multiple iterations.
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22 Apple 18
87.5K Views
High Frequency
~25 min Avg. Time
3.2K 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