Hard

Quiz

#135 Candy

APPROACH

n children stand in a row, each assigned a rating from the integer array ratings.

Distribute candies under these rules:

- Every child must receive at least one candy.

- A child with a higher rating than a neighbor must receive more candies than that neighbor.

Return the minimum total number of candies needed.

Example 1:

Input: ratings = [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: ratings = [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
1 of 4
1:00

What is the optimal approach for this problem?