Skip to content
Problem 135 · LeetCode 135(opens in a new tab)

Candy

HardArrays

A row of children each has a rating, given as the array ratings. You are handing out candy under two rules: every child gets at least one piece, and a child whose rating is higher than a neighbour's must end up with more candy than that neighbour.

Return the smallest total number of candies that satisfies both rules. Neighbours with equal ratings owe each other nothing.

Example 1

Input:  ratings = [2, 4, 3, 1, 5]
Output: 9
Why:    hand out 1, 3, 2, 1, 2
2 more examples and the constraints

Example 2

Input:  ratings = [3, 3, 3]
Output: 3
Why:    equal ratings need no extra candy

Example 3

Input:  ratings = [5, 4, 3, 2]
Output: 10
Why:    a falling line needs 4, 3, 2, 1

Constraints

  • 1 ≤ length of ratings ≤ 50,000
  • 0 ≤ each rating ≤ 50,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Fix until nothing changesO(n²)
  2. Two passes, one per sideO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 childrenVerdict
Fix until nothing changesO(n²)
Correct, but falling runs crawl
Two passes, one per sideO(n)
Best; two sweeps, done

n = number of children.

Edge cases to test

  • One child. [7] needs exactly 1 candy.
  • Equal neighbours. [1, 2, 2, 1] gives 1, 2, 2, 1 = 6: the two 2s do not need to differ.
  • Strictly falling line. [5, 4, 3, 2] only gets fixed by the backward pass: 4, 3, 2, 1.
  • Peak. [1, 3, 5, 3, 1] gives 1, 2, 3, 2, 1 = 9; the peak takes the larger of its two sides.

Common mistakes

  • Overwriting the left-pass value on the backward pass instead of taking the max, which breaks the left rule at peaks.
  • Giving equal-rated neighbours different counts, which wastes candy.
  • Doing both checks in a single forward pass and missing long falling runs.

How to talk through it

  1. 1Clarify. Do equal ratings need equal candy? Only adjacent children count, right?
  2. 2Give the brute force. Start everyone at 1 and fix broken pairs until stable; a falling line makes it O(n²).
  3. 3Split the rule. The left rule and the right rule are each easy in one sweep, in opposite directions.
  4. 4Code the two passes. Forward sets left counts; backward takes the max with right count plus one.
  5. 5Test out loud. Run one child, a flat line, a falling line and a peak.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?