Paths Subjects Questions Quizzes Pricing Search
Advanced Open Pro

Candies

There are n children standing in a line, each with a rating given by an integer array ratings. You must distribute candies to the children subject to two rules:

  • Every child must receive at least one candy.
  • Any child with a strictly higher rating than one of their immediate neighbors must receive strictly more candies than that neighbor.

Return the minimum total number of candies you need to satisfy both rules.

Example 1

Input: ratings = [1, 0, 2]
Output: 5
Explanation: One valid distribution is [2, 1, 2]: the middle
child has the lowest rating and gets the minimum of 1 candy, and
both neighbors, having higher ratings than the middle child, get
more than it. Total = 2 + 1 + 2 = 5.

Example 2

Input: ratings = [1, 2, 2]
Output: 4
Explanation: One valid distribution is [1, 2, 1]. The third child
gets 1 candy, satisfying the "at least 1" rule; since the third
child's rating is equal (not strictly higher) to the second
child's, no extra candy is required there. Total = 1 + 2 + 1 = 4.

Constraints

  • n == ratings.length
  • 1 <= n <= 2 * 10^4
  • 0 <= ratings[i] <= 2 * 10^4

Share this question

← Back to Greedy practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.