Candy
Hard Greedy AI round
ratings holds the score of each child standing in a line, in the order they stand. You give each child some candy.
Every child gets at least one piece, and a child with a higher score than a neighbour gets more pieces than that neighbour. Two neighbours with equal scores may get any amounts.
Return the fewest pieces of candy, counted over the whole line, that keep both rules.
Example 1
Input: ratings = [2,5,7,4,1]
Output: 9
The scores rise to 7 and fall after it, so the pieces go 1, 2, 3, 2, 1: 9 in all. The child with 7 needs more than both neighbours, who need 2 each.
Example 2
Input: ratings = [3,3,3,3]
Output: 4
Example 3
Input: ratings = [6,2,8,8,1,4]
Output: 10
Constraints
1 ≤ ratings.length ≤ 6 × 10⁴0 ≤ ratings[i] ≤ 10⁹- The answer is at most 1,800,030,000 (6 × 10⁴ children with rising scores), so it fits in a 32-bit signed integer
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Greedy
- Gas StationAI round · Medium
- Largest NumberAI round · Medium
- Increasing Triplet SubsequenceMedium
- Minimum Number of Arrows to Burst BalloonsMedium
- Can Place FlowersEasy