FunctionRacerProblemsRace

Fewest Candies by Rating

MediumGreedyPython, JavaScript, TypeScript, Java, C++

Children stand in a row and ratings[i] is the rating of child i. You hand out candies under two rules: every child gets at least one candy, and a child with a strictly higher rating than a neighbour (the child just before or just after them) must get strictly more candies than that neighbour. Children with equal ratings may get any amounts.

Return the fewest candies that satisfy both rules in total. The fewest total is unique, so no tie rule is needed. Return 0 when ratings is empty.

Example 1

ratings [1,0,2]
returns 5

Candies 2, 1, 2: the middle child has the lowest rating and gets one, both neighbours need more.

Example 2

ratings [1,2,2]
returns 4

Candies 1, 2, 1: the third child has the same rating as the second, so one candy is enough there.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Greedy problems