Problems/Greedy/Candies
Greedy
hard

Candies

The 'Treat Distribution' problem focuses on fairly distributing treats to children based on their performance ratings, ensuring those with higher ratings receive more treats than their neighbors. This problem tests your ability to think greedily and optimize resource allocation based on local information, a common scenario in real-world scheduling and optimization tasks.

arraygreedyoptimizationdynamic-programming

Problem Statement

You are tasked with distributing treats to a line of children. Each child has a performance rating represented by an integer. You must distribute treats such that every child receives at least one treat, and children with higher ratings receive strictly more treats than their immediate neighbors (left and right). Determine the minimum number of treats needed to satisfy these conditions.

Example 1
Input: [1, 0, 2]
Output: 5
The treat distribution could be [2, 1, 2]. The child with rating 1 gets 2 treats, the child with rating 0 gets 1 treat, and the child with rating 2 gets 2 treats. The total number of treats is 2 + 1 + 2 = 5.
Example 2
Input: [1, 2, 2, 1]
Output: 6
The treat distribution could be [1, 2, 1, 2]. The child with rating 1 gets 1 treat, the next child with rating 2 gets 2 treats, then the next child with rating 2 gets 1 treat, and the child with rating 1 gets 2 treats. The total number of treats is 1 + 2 + 1 + 2 = 6.
Constraints
  • -n == ratings.length
  • -1 <= n <= 2 * 10^4
  • -0 <= ratings[i] <= 10^4

Brute Force Approach

The most straightforward approach is to repeatedly iterate through the children and adjust the treat distribution until all conditions are met. Imagine you're repeatedly checking each child and giving them an extra treat if they deserve more than their neighbor, continuing until no more adjustments are needed. This is inefficient because you might have to revisit children multiple times. The time complexity is high because of these repeated checks, and space complexity is low as we only modify the existing array.

TimeO(n^2)
SpaceO(1)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem