Candy

Hard

Children stand in a line with ratings[i]. Every child must receive at least one candy, and a child with a higher rating than a neighbour must receive more.

Return the minimum number of candies needed.

Example 1

candy()
Input
ratings = [1,0,2]
Output
5

Why

[2,1,2]

Example 2

candy()
Input
ratings = [1,2,2]
Output
4

Why

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

Topics

ArraysGreedy

Implement candy in the editor and return the answer — printing it is never graded.