135. Candy #1758
-
Topics: There are 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:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to distribute candies to children standing in a line such that each child gets at least one candy, and children with higher ratings than their neighbors receive more candies. The goal is to determine the minimum number of candies required to meet these conditions. Approach
Let's implement this solution in PHP: 135. Candy <?php
/**
* @param Integer[] $ratings
* @return Integer
*/
function candy($ratings) {
$n = count($ratings);
$candies = array_fill(0, $n, 1);
for ($i = 1; $i < $n; $i++) {
if ($ratings[$i] > $ratings[$i - 1]) {
$candies[$i] = $candies[$i - 1] + 1;
}
}
for ($i = $n - 2; $i >= 0; $i--) {
if ($ratings[$i] > $ratings[$i + 1]) {
$candies[$i] = max($candies[$i], $candies[$i + 1] + 1);
}
}
return array_sum($candies);
}
// Example 1
$ratings = [1, 0, 2];
echo "Output: " . candy($ratings) . "\n"; // Output: 5
// Example 2
$ratings = [1, 2, 2];
echo "Output: " . candy($ratings) . "\n"; // Output: 4
?> Explanation:
This approach efficiently satisfies the problem constraints by making two passes over the array, ensuring optimal candy distribution with minimal total candies. The complexity is O(n) time and O(n) space, where n is the number of children. |
Beta Was this translation helpful? Give feedback.
We need to distribute candies to children standing in a line such that each child gets at least one candy, and children with higher ratings than their neighbors receive more candies. The goal is to determine the minimum number of candies required to meet these conditions.
Approach