CodingNodes / Arrays & Hashing / Candy System design Space play · ←→ step · R restart

Problem

Children stand in a row and each has a rating, given in ratings. You hand out candy under two rules: every child gets at least one piece, and a child with a higher rating than an adjacent child must get more candy than that neighbour.

Return the smallest total number of candies that satisfies both rules.

Constraints

  • 1 ≤ ratings.length ≤ 2 · 10⁴
  • 0 ≤ ratings[i] ≤ 2 · 10⁴

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Two linear sweeps over the array plus one sum.

Space: One candy count per child.

Satisfy each rule separately. A left-to-right pass makes every child with a higher rating than the left neighbour get one more than that neighbour. A right-to-left pass does the same for the right neighbour, taking the larger of the two requirements so the first pass is never undone. Then add up the candies.