|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +// Time Complexity : O(m + n), |
| 4 | +// where 'm' is the length of 'rolls', and 'n' is 'n'. |
| 5 | +// We traverse 'rolls' to get the sum, and traverse the result array of size 'n' to populate the missing observations. |
| 6 | +// |
| 7 | +// Space Complexity : O(n), |
| 8 | +// where 'n' is the input variable 'n'. |
| 9 | +// The result has a size of 'n'. |
| 10 | + |
| 11 | +public class FindMissingObservations { |
| 12 | + |
| 13 | + // Approach: |
| 14 | + // Arithmetically determine the sum of the 'n' rolls by first getting the sum of the 'm' rolls. |
| 15 | + // Then determine the average roll for the 'n' rolls and its remainders to assign the correct rolls. |
| 16 | + // If sum = 10, n = 4, the average roll is 10 / 4 == 2, with remainder of 2. Thus, we know to assign [3,3,2,2] |
| 17 | + |
| 18 | + public int[] missingRolls(int[] rolls, int mean, int n) { |
| 19 | + // Determine the sum of 'n' rolls. |
| 20 | + int sumM = 0; |
| 21 | + for (int roll : rolls) sumM += roll; |
| 22 | + int sumN = mean * (rolls.length + n) - sumM; |
| 23 | + |
| 24 | + // If the sum for 'n' rolls is: |
| 25 | + // - less than all 'n' rolls of 1, or |
| 26 | + // - greater than all 'n' rolls of 6, |
| 27 | + // then we know it is impossible to get the target with 'n' rolls. |
| 28 | + if (sumN < n || sumN > 6 * n) return new int[0]; |
| 29 | + |
| 30 | + // Determine the 'floor' number, and the 'remainder' for the number of rolls to add 1 to the 'floor'. |
| 31 | + int floor = sumN / n; |
| 32 | + int remainder = sumN % n; |
| 33 | + int[] result = new int[n]; |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + result[i] = remainder-- > 0 ? floor + 1 : floor; |
| 36 | + } |
| 37 | + return result; |
| 38 | + } |
| 39 | +} |
0 commit comments