candies
with the same length as ratings
, filling it with 1s, since each child must have at least one candy.ratings
array from left to right. For each child, if they have a higher rating than the child to their left, give them one more candy than the child to their left.ratings
array from right to left. For each child, if they have a higher rating than the child to their right and they do not already have more candies, give them one more candy than the child to their right.candies
array to get the total number of candies needed.