Leetcode Problem 135. Candy

135. Candy

Leetcode Solutions

Approach: Using one array

  1. Initialize an array candies with the same length as ratings, filling it with 1s, since each child must have at least one candy.
  2. Traverse the 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.
  3. Traverse the 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.
  4. Sum up all the values in the candies array to get the total number of candies needed.
UML Thumbnail

Approach: Brute Force

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...