Skip to content
Decoder

Candy

Hard

Problem

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.

Example 1

Input
ratings = [1, 0, 2]
Output
5
Why
2, 1, 2

Example 2

Input
ratings = [1, 2, 2]
Output
4
Why
1, 2, 1: equal ratings need not match

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.