Candy

hard

There are n children standing in a line, each with a rating value. You are handing out candies under two rules:

  • Every child gets at least one candy.
  • A child with a higher rating than an adjacent neighbor gets more candies than that neighbor.

Return the minimum total number of candies you must give out.

Hints

Each child has two neighbors — can one left-to-right pass respect both?
Do two passes: one left-to-right for left neighbors, one right-to-left for right neighbors.
Combine them by taking the maximum requirement at each child.

Common doubts

Going left to right, you don't yet know a child's right neighbor's final candy count. A second pass in the opposite direction supplies that side.
The left pass may have already given a child a high value to beat its left neighbor. The right pass must not lower that, so it takes the larger of the existing value and (right neighbor + 1).
No rule applies between equal ratings, so neither child is forced to have more than the other — they can both stay low, which minimizes the total.

Interview follow-ups

Yes — a single pass can track the lengths of the current increasing and decreasing runs and add the candy contributions arithmetically, avoiding the candies array.
The wrap-around creates a cyclic dependency that a simple two-pass can't resolve directly; you'd detect and break the cycle or iterate to a fixed point.

Fun facts

  • This two-pass 'reconcile both directions' pattern also computes, for each element, the span to the next greater element on each side.
  • Candy is a favorite hard-tagged interview greedy precisely because the naive one-pass attempt looks right but silently undercounts.

Asked at

AmazonGoogleMicrosoftUber
Frequently Sometimes Occasionally
Example 1
Input: ratings = [1,0,2]
Output: 5
Give 2, 1, 2 candies to the three children respectively.
Example 2
Input: ratings = [1,2,2]
Output: 4
Give 1, 2, 1 candies. The last two children have equal ratings, so the third can get just one.
Constraints

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

Solve this problem →