#135
Candy
candidate master · 1485 · lc hard +32 · verified · 48% accepted · 9,280 likes · top 33%
Description
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.
Code
1
2
3