Design Gurus Logo
Candy (hard)

Problem Statment

You are given ratings array of integers where ratings[i] is rating value assigned to the i<sup>th</sup> child. You are giving candies to these n children who are standing in single row.

Follow below rules to give candies to each child:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

Return the minimum count of candies you require to distribute candies to the children.

Examples

  • Example 1:

    • Input: ratings = [4, 2, 3, 4]
    • Expected Output: 8
    • Justification: The second child gets 1 candy (lowest rating), the third gets 2 candies (higher than the second), the first gets 2 (higher than the second but equal to the third), and the fourth gets 3 (highest rating).
  • Example 2:

    • Input: ratings = [1, 1, 1]
    • Expected Output: 3
    • Justification: All children have the same rating, so each gets 1 candy to satisfy the minimum requirement.
  • Example 3:

    • Input: ratings = [2, 4, 2, 6, 1, 7, 8]
    • Expected Output: 12
    • Justification: We can give candies to each child as given in [1, 2, 1, 2, 1, 2, 3], totaling 12 candies.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory