781. Rabbits in Forest #1585
-
Topics: There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array Given the array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of rabbits in a forest based on the answers provided by the rabbits. Each rabbit's answer indicates how many other rabbits share the same color. Our task is to compute the minimum possible number of rabbits that could be present in the forest given these answers. Approach
Let's implement this solution in PHP: 781. Rabbits in Forest <?php
/**
* @param Integer[] $answers
* @return Integer
*/
function numRabbits($answers) {
$freq = array();
foreach ($answers as $ans) {
if (isset($freq[$ans])) {
$freq[$ans]++;
} else {
$freq[$ans] = 1;
}
}
$total = 0;
foreach ($freq as $x => $cnt) {
if ($x == 0) {
$total += $cnt;
} else {
$denominator = $x + 1;
$groups = (int)(($cnt + $x) / $denominator);
$total += $groups * $denominator;
}
}
return $total;
}
// Test cases
echo numRabbits(array(1, 1, 2)) . "\n"; // Output: 5
echo numRabbits(array(10, 10, 10)) . "\n"; // Output: 11
?> Explanation:
This approach efficiently computes the minimum number of rabbits by leveraging grouping based on the answers, ensuring optimal group sizes to minimize the total count. |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of rabbits in a forest based on the answers provided by the rabbits. Each rabbit's answer indicates how many other rabbits share the same color. Our task is to compute the minimum possible number of rabbits that could be present in the forest given these answers.
Approach
x
, we need to determine the minimum number of groups required. Each group of rabbits that answeredx
must have exactlyx + 1
rabbits (since a rabbit answeringx
implies there arex
other rabbits of t…