|
| 1 | +/** |
| 2 | + * 2028. Find Missing Observations |
| 3 | + * https://leetcode.com/problems/find-missing-observations/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n |
| 7 | + * of the observations went missing, and you only have the observations of m rolls. |
| 8 | + * Fortunately, you have also calculated the average value of the n + m rolls. |
| 9 | + * |
| 10 | + * You are given an integer array rolls of length m where rolls[i] is the value of the ith |
| 11 | + * observation. You are also given the two integers mean and n. |
| 12 | + * |
| 13 | + * Return an array of length n containing the missing observations such that the average |
| 14 | + * value of the n + m rolls is exactly mean. If there are multiple valid answers, return |
| 15 | + * any of them. If no such array exists, return an empty array. |
| 16 | + * |
| 17 | + * The average value of a set of k numbers is the sum of the numbers divided by k. |
| 18 | + * |
| 19 | + * Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} rolls |
| 24 | + * @param {number} mean |
| 25 | + * @param {number} n |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var missingRolls = function(rolls, mean, n) { |
| 29 | + const totalRolls = rolls.length + n; |
| 30 | + const targetSum = mean * totalRolls; |
| 31 | + const currentSum = rolls.reduce((sum, roll) => sum + roll, 0); |
| 32 | + const missingSum = targetSum - currentSum; |
| 33 | + |
| 34 | + if (missingSum < n || missingSum > 6 * n) return []; |
| 35 | + |
| 36 | + const baseValue = Math.floor(missingSum / n); |
| 37 | + const remainder = missingSum % n; |
| 38 | + const result = []; |
| 39 | + |
| 40 | + for (let i = 0; i < n; i++) { |
| 41 | + if (i < remainder) { |
| 42 | + result.push(baseValue + 1); |
| 43 | + } else { |
| 44 | + result.push(baseValue); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return result; |
| 49 | +}; |
0 commit comments