2226. Maximum Candies Allocated to K Children #1430
-
Topics: You are given a 0-indexed integer array You are also given an integer Return the maximum number of candies each child can get. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the maximum number of candies each child can get such that each child receives the same number of candies from a single pile (or sub-pile). The solution involves using binary search to efficiently find this maximum number of candies. Approach
Let's implement this solution in PHP: 2226. Maximum Candies Allocated to K Children <?php
/**
* @param Integer[] $candies
* @param Integer $k
* @return Integer
*/
function maximumCandies($candies, $k) {
$sum = array_sum($candies);
if ($sum < $k) {
return 0;
}
$left = 1;
$right = max($candies);
$ans = 0;
while ($left <= $right) {
$mid = $left + intdiv(($right - $left), 2);
$total = 0;
foreach ($candies as $c) {
$total += intdiv($c, $mid);
if ($total >= $k) {
break;
}
}
if ($total >= $k) {
$ans = $mid;
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return $ans;
}
// Example Test Cases
echo maximumCandies([5,8,6], 3) . "\n"; // Output: 5
echo maximumCandies([2,5], 11) . "\n"; // Output: 0
?> Explanation:
This approach efficiently narrows down the possible values using binary search, ensuring we find the maximum number of candies each child can receive in logarithmic time relative to the maximum pile size, making it suitable for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to determine the maximum number of candies each child can get such that each child receives the same number of candies from a single pile (or sub-pile). The solution involves using binary search to efficiently find this maximum number of candies.
Approach
c
, we can check if it's possible to distributec
candies to each ofk
children by summing the number of sub-piles each pile can contribute (each sub-pile must have at leastc
candies). This sum must be at leastk
for the distribution to be possible.c
. The search range …