#135

Candy

Hard Two passes

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Children stand in a line with ratings. Each gets at least one candy, and a child with a higher rating than a neighbour must get more than that neighbour. Return the minimum total.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: fewest candies so higher-rated kids get more than their neighbours.

Why this works: one pass fixes the left neighbour rule, one pass from the right fixes the right neighbour rule (take the max).

Example: ratings [1, 0, 2]

left pass:  [1, 1, 2]right pass: [2, 1, 2] → 5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Overwriting in the second pass instead of taking the max, which breaks the left rule.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Greedy
🎬 Episodes 69–73: video coming soon