21. Candy

The problem can be found at the following link: Question Link

My Approach

  • I use a two-pass approach to calculate the minimum number of candies required.

  • First, I iterate from left to right, checking if the current rating is greater than the previous one. If true, I increment the count of candies for the current child.

  • Next, I iterate from right to left, checking if the current rating is greater than the next one. If true, I update the count of candies for the current child to the maximum of its current value and the count from the right side.

  • Finally, I iterate through the ratings again, adding the maximum count of candies for each child to the total.

Time and Auxiliary Space Complexity

  • Time Complexity: O(N) - We iterate through the ratings array three times.

  • Auxiliary Space Complexity: O(N) - We use two additional arrays of size N for left and right.

Code (C++)

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.

Last updated

Was this helpful?