Candy

Hard

Topics
ArrayGreedy

There are n children with ratings. Each child gets at least one candy, and a child with a higher rating than an adjacent child must get more candies. Return the minimum total candies.

Example 1

rating102
candy212
Each child needs more sweets than a lower-rated neighbour, on both sides. Total 5.
Top row is ratings; bottom row is the sweets each child ends up with.
Input:  ratings = [1,0,2]
Output: 5

Example 2

rating122
candy121
Input:  ratings = [1,2,2]
Output: 4

Constraints

  • n == ratings.length
  • 1 <= n <= 2*10^4
  • 0 <= ratings[i] <= 2*10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

There are two constraints and they pull in opposite directions: every child needs at least one candy, and a child rated higher than a neighbour needs strictly more than that neighbour. We want the smallest total that satisfies both.

The brute force is to start everyone at 1 and repeatedly sweep the array, bumping any child who violates the rule against a neighbour, until a full pass changes nothing. That is correct — it is just constraint relaxation — but each pass is O(n) and the number of passes depends on the longest increasing run, so a monotonic ramp of length n makes it O(n^2).

The relaxation is wasteful because it rediscovers the same thing repeatedly. The useful observation is that the two neighbours are independent constraints. A child's candy count has to beat the left neighbour if the left rating is lower, and beat the right neighbour if the right rating is lower. Nothing couples those two demands except that both must hold.

So compute them separately and combine. One left-to-right pass satisfies every "greater than my left neighbour" constraint; one right-to-left pass satisfies every "greater than my right neighbour" constraint. The answer for each child is the maximum of the two demands, because that is the smallest number satisfying both.

Taking the max is the whole trick, and it is worth being clear about why it is safe rather than just asserting it. The left pass gives each child enough to beat their left neighbour; raising a value never breaks a "greater than" constraint that was already satisfied against a lower neighbour. So lifting a child to meet the right-side demand cannot invalidate the left-side one, and vice versa. The two passes compose without interfering.

Approach

  1. Start every child at 1, which satisfies the "at least one" rule on its own.
  2. Left to right: if ratings[i] > ratings[i-1], set candy[i] = candy[i-1] + 1. Assignment, not max, because the left pass is the sole authority on left-side constraints at this point.
  3. Right to left: if ratings[i] > ratings[i+1], set candy[i] = max(candy[i], candy[i+1] + 1). This one must be a max, or it would overwrite the left pass's work.
  4. Sum the array.

Dry Run

ratings = [1, 0, 2], expected 5.

init                        [1, 1, 1]

left pass
  i=1: 0 <= 1, no demand    [1, 1, 1]
  i=2: 2 >  0, c[2]=c[1]+1  [1, 1, 2]

right pass
  i=1: 0 <= 2, no demand    [1, 1, 2]
  i=0: 1 >  0, c[0]=max(1, c[1]+1)=2
                            [2, 1, 2]

total 5

Now the case that shows why the max matters — ratings = [1, 2, 87, 87, 87, 2, 1]:

after left pass   [1, 2, 3, 1, 1, 1, 1]
after right pass  [1, 2, 3, 1, 3, 2, 1]   total 13

Index 2 keeps the 3 the left pass gave it, because its right neighbour is equal and makes no demand. Index 4 is raised from 1 to 3 by the right pass alone. Equal ratings are the quiet case: 87 next to 87 imposes nothing in either direction, so the ramp resets rather than continuing.

Complexity

  • Time — O(n): two linear passes and a sum, so 3n operations and no nesting. Against the O(n^2) worst case of sweeping until stable, which a single long increasing run triggers.
  • Space — O(n): the candy array. This is genuinely needed, because the right pass has to read what the left pass decided. It can be reduced to O(1) by walking the array once and accounting for each up-slope and down-slope with running counts, handling the peak by taking the larger of the two slope lengths — same O(n) time, no array, considerably easier to get wrong. Worth naming if asked to improve the space.

Common Pitfalls

  • Using = instead of max(...) in the second pass, which silently discards the left pass. The smallest input that exposes it is [1,2,3,1]: the correct answer is 7, the bug gives 6, producing [1,2,2,1] where index 2 is rated higher than index 1 but holds the same two candies. Note that many inputs — including [1,3,2] and [1,2,87,87,87,2,1] — give the right total either way, so this is a bug that passes casual testing.
  • Treating equal ratings as needing different amounts. The rule only fires on a strict inequality, so [2,2,2] is three candies total, not six.
  • Comparing candy counts rather than ratings in the pass conditions. The condition is about ratings; the assignment is about candy.
  • Running both passes in one loop. The right-side demand for index i depends on index i+1, which is not yet settled on a forward pass, so the directions cannot be fused.
  • Initialising to 0. Every child needs at least one candy, and starting at 0 makes flat stretches free.
  • Assuming the greedy needs proof by exchange argument. It does not — each child is given the minimum that satisfies both constraints independently, so the total is minimal by construction.

Full Solution — all languages

class Solution:
    def candy(self, nums):
        n = len(nums)
        c = [1] * n
        for i in range(1, n):
            if nums[i] > nums[i - 1]:
                c[i] = c[i - 1] + 1
        for i in range(n - 2, -1, -1):
            if nums[i] > nums[i + 1]:
                c[i] = max(c[i], c[i + 1] + 1)
        return sum(c)
SensAI
Beta
Tap the mic to stop voice mode