Skip to content

Candy

HardGreedy
Decode it first. Clues, constraints, pattern and plan before any code.

Children stand in a line, and child i has a rating ratings[i]. Hand out candy so that:

  • every child gets at least one candy, and
  • a child with a higher rating than a neighbour gets more candy than that neighbour.

Return the minimum total candy you need.

ratings = [1, 0, 2]  →  5   (2, 1, 2)
ratings = [1, 2, 2]  →  4   (1, 2, 1: equal ratings need not match)

Constraints

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