There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. You are giving candies to these children subject to two requirements: every child must have at least one candy, and children with a higher rating than their adjacent neighbors must get more candies. Return the minimum number of candies needed.
ratings = [1,0,2]5ratings = [1,2,2]4c[i] = 1 (every child gets at least 1 candy)ratings[i] > ratings[i-1] → c[i] = c[i-1] + 1ratings[i] > ratings[i+1] → c[i] = max(c[i], c[i+1] + 1)sum(c) — minimum candies satisfying all constraintsA single left-to-right pass only ensures every child has more candy than their left neighbor when needed. The right-to-left pass then ensures the right neighbor constraint. Taking the max during Pass 2 preserves whatever Pass 1 already set — guaranteeing both constraints are satisfied simultaneously with the minimum total.
Repeatedly fixing violations until none remain can take O(n²). Each child really has two separate rules, one for the left neighbour and one for the right.
Give everyone 1 candy to start. Left to right, if a rating is higher than the left neighbour, give one more than that neighbour. Right to left, if a rating is higher than the right neighbour, take the bigger of its value and the right neighbour plus 1.
Split a two-sided rule into two one-sided passes. Take the maximum so both rules hold.
Run the animation above on your own input, or watch the 1:25 video explanation of Candy with a dry run and Java code.