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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code