Gamified challenge · Two-pass greedy
Children stand in a line; ratings[i] is child i's rating. Every child gets at least one candy, and a child with a higher rating than a neighbour must get more candy than that neighbour. Equal ratings carry no rule.
Write minCandy(ratings) that returns the fewest candies in total that satisfy both rules. For [1, 0, 2] the answer is 5 (give 2, 1, 2); for [1, 2, 2] it is 4 (give 1, 2, 1).
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google