2028. Find Missing Observations #482
-
Topics: You have observations of You are given an integer array Return an array of length The average value of a set of Note that Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine an array of missing rolls such that the average of all Steps to Approach:
Let's implement this solution in PHP: 2028. Find Missing Observations <?php
/**
* @param Integer[] $rolls
* @param Integer $mean
* @param Integer $n
* @return Integer[]
*/
function missingRolls($rolls, $mean, $n) {
// Calculate the total sum needed for n + m rolls
$m = count($rolls);
$total_sum = ($n + $m) * $mean;
// Calculate the sum of the given rolls
$sum_rolls = array_sum($rolls);
// Calculate the sum required for the missing rolls
$missing_sum = $total_sum - $sum_rolls;
// Check if the missing sum is within the valid range
if ($missing_sum < $n || $missing_sum > 6 * $n) {
return []; // Impossible to find valid missing rolls
}
// Initialize the result array with the minimum value 1
$result = array_fill(0, $n, 1);
$remaining_sum = $missing_sum - $n; // Already allocated n * 1 = n, so subtract this
// Distribute the remaining sum to the rolls
for ($i = 0; $i < $n && $remaining_sum > 0; $i++) {
$add = min(5, $remaining_sum); // Add at most 5 to keep the value <= 6
$result[$i] += $add;
$remaining_sum -= $add;
}
return $result;
}
// Example 1
$rolls = [3, 2, 4, 3];
$mean = 4;
$n = 2;
print_r(missingRolls($rolls, $mean, $n));
// Example 2
$rolls = [1, 5, 6];
$mean = 3;
$n = 4;
print_r(missingRolls($rolls, $mean, $n));
// Example 3
$rolls = [1, 2, 3, 4];
$mean = 6;
$n = 4;
print_r(missingRolls($rolls, $mean, $n));
?> Explanation:
Time Complexity:
This solution ensures that we either find valid missing rolls or return an empty array when no solution exists. |
Beta Was this translation helpful? Give feedback.
We need to determine an array of missing rolls such that the average of all
n + m
dice rolls is exactly equal tomean
. Here's the step-by-step breakdown of the solution:Steps to Approach:
Calculate the total sum for
n + m
rolls:Given that the average value of
n + m
rolls ismean
, the total sum of all the rolls should betotal_sum = (n + m) * mean
.Determine the missing sum:
The sum of the
m
rolls is already known. Thus, the sum of the missingn
rolls should be:where
∑(rolls)
is the sum of the elements in therolls
array.Check for feasibility:
Each roll is a 6-sided die, so the missing values must be between 1 and 6 (inclusive). Therefore, the …