There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
Return the minimum number of candies you need to have to distribute the candies to the children.
Example 1:
Input: ratings = [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: ratings = [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
Constraints:
n == ratings.length1 <= n <= 2 * 1040 <= ratings[i] <= 2 * 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to distribute candies to a line of children based on their scores, where higher-scoring children get more candies than their immediate neighbors. The brute force approach involves testing every possible combination of candy amounts for each child until you find a valid distribution that uses the fewest total candies.
Here's how the algorithm would work step-by-step:
def candy(ratings):
# We use recursion to generate and test every single valid candy distribution permutation
def generate_distributions(current_index, current_distribution):
if current_index == len(ratings):
if satisfies_rules(current_distribution):
valid_combinations.append(list(current_distribution))
return
for candy_amount in range(1, len(ratings) + 1):
current_distribution.append(candy_amount)
generate_distributions(current_index + 1, current_distribution)
current_distribution.pop()
def satisfies_rules(distribution):
for index in range(len(ratings)):
if index > 0 and ratings[index] > ratings[index - 1] and distribution[index] <= distribution[index - 1]:
return False
if index < len(ratings) - 1 and ratings[index] > ratings[index + 1] and distribution[index] <= distribution[index + 1]:
return False
return True
valid_combinations = []
generate_distributions(0, [])
# We compare all successful combinations to isolate the one consuming the absolute minimum total candies
minimum_total_candies = float('inf')
for combination in valid_combinations:
total_candies = sum(combination)
if total_candies < minimum_total_candies:
minimum_total_candies = total_candies
return minimum_total_candiesInstead of trying to figure out everyone's candy amount all at once, the optimal approach breaks the puzzle down by looking at neighbors in two separate passes. First, we ensure that anyone with a higher score than the person immediately to their left gets more candy than that neighbor, and then we do a second pass from the other direction to fix the right-hand neighbors.
Here's how the algorithm would work step-by-step:
class Solution:
def candy(self, ratings: list[int]) -> int:
total_children = len(ratings)
candy_allocations = [1] * total_children
# Enforce left-to-right rule so higher rated children get more than left neighbor.
for current_index in range(1, total_children):
if ratings[current_index] > ratings[current_index - 1]:
candy_allocations[current_index] = candy_allocations[current_index - 1] + 1
# Enforce right-to-left rule to satisfy conditions relative to right neighbor.
for current_index in range(total_children - 2, -1, -1):
if ratings[current_index] > ratings[current_index + 1]:
if candy_allocations[current_index] <= candy_allocations[current_index + 1]:
candy_allocations[current_index] = candy_allocations[current_index + 1] + 1
# Sum all individual allocations to determine the absolute minimum total required.
return sum(candy_allocations)| Case | How to Handle |
|---|---|
| Empty or null ratings array | Return zero immediately as no children need candy. |
| Single child rating | Return one because the single child must receive the minimum requirement of one candy. |
| Two children with identical ratings | Assign one candy to each since neither has a strictly higher rating than the other. |
| All children have identical ratings | The two-pass algorithm assigns one candy to every child since no neighbor has a strictly higher rating. |
| Strictly monotonically increasing ratings | The forward pass correctly increments each child's candy count sequentially from one upwards. |
| Strictly monotonically decreasing ratings | The backward pass correctly ensures each child gets strictly more candies than their right neighbor from the end. |
| V-shaped ratings where the lowest rating is in the middle | The combination of left-to-right and right-to-left passes correctly takes the maximum of both directional requirements at the lowest point. |
| Extremely large rating values | Using standard integer accumulators for the total candy count prevents overflow since sums scale linearly with array length rather than rating magnitude. |