Candy
There are n children in a line, each with a rating given in the array ratings. Every child must get at least one candy, and any child with a higher rating than an immediate neighbor must receive more candies than that neighbor. Return the minimum total number of candies you must give out.
Open official problem prompt ↗Hand out the fewest candies possible while honoring 'higher rating than a neighbor means strictly more candy' in both directions.
Like leveling a row of stacked blocks by walking the line twice: once forward raising each block above a shorter left neighbor, once backward raising it above a shorter right neighbor, then keeping whichever height each block needed.
- Input
- ratings = [1, 0, 2]
- Output
- 5
- Why
- Give candies [2, 1, 2]: the middle child has the lowest rating and gets 1, and each higher-rated neighbor gets more, totaling 5.
n == ratings.length1 <= n <= 2 * 10^40 <= ratings[i] <= 2 * 10^4