|
| 1 | +/** |
| 2 | + * 1223. Dice Roll Simulation |
| 3 | + * https://leetcode.com/problems/dice-roll-simulation/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint |
| 7 | + * to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) |
| 8 | + * consecutive times. |
| 9 | + * |
| 10 | + * Given an array of integers rollMax and an integer n, return the number of distinct sequences |
| 11 | + * that can be obtained with exact n rolls. Since the answer may be too large, return it modulo |
| 12 | + * 1e9 + 7. |
| 13 | + * |
| 14 | + * Two sequences are considered different if at least one element differs from each other. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number} n |
| 19 | + * @param {number[]} rollMax |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var dieSimulator = function(n, rollMax) { |
| 23 | + const MOD = 1e9 + 7; |
| 24 | + const faces = 6; |
| 25 | + |
| 26 | + const dp = new Array(n + 1).fill().map(() => new Array(faces).fill(0)); |
| 27 | + for (let face = 0; face < faces; face++) { |
| 28 | + dp[1][face] = 1; |
| 29 | + } |
| 30 | + |
| 31 | + for (let rolls = 2; rolls <= n; rolls++) { |
| 32 | + for (let face = 0; face < faces; face++) { |
| 33 | + const maxConsecutive = Math.min(rolls, rollMax[face]); |
| 34 | + let sequences = 0; |
| 35 | + |
| 36 | + for (let streak = 1; streak <= maxConsecutive; streak++) { |
| 37 | + if (streak === rolls) { |
| 38 | + sequences = (sequences + 1) % MOD; |
| 39 | + } else { |
| 40 | + let prevCombinations = 0; |
| 41 | + for (let prevFace = 0; prevFace < faces; prevFace++) { |
| 42 | + if (prevFace !== face) { |
| 43 | + prevCombinations = (prevCombinations + dp[rolls - streak][prevFace]) % MOD; |
| 44 | + } |
| 45 | + } |
| 46 | + sequences = (sequences + prevCombinations) % MOD; |
| 47 | + } |
| 48 | + } |
| 49 | + dp[rolls][face] = sequences; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + let result = 0; |
| 54 | + for (let face = 0; face < faces; face++) { |
| 55 | + result = (result + dp[n][face]) % MOD; |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | +}; |
0 commit comments