|
| 1 | +/** |
| 2 | + * 3405. Count the Number of Arrays with K Matching Adjacent Elements |
| 3 | + * https://leetcode.com/problems/count-the-number-of-arrays-with-k-matching-adjacent-elements/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given three integers n, m, k. A good array arr of size n is defined as follows: |
| 7 | + * - Each element in arr is in the inclusive range [1, m]. |
| 8 | + * - Exactly k indices i (where 1 <= i < n) satisfy the condition arr[i - 1] == arr[i]. |
| 9 | + * |
| 10 | + * Return the number of good arrays that can be formed. |
| 11 | + * |
| 12 | + * Since the answer may be very large, return it modulo 109 + 7. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number} n |
| 17 | + * @param {number} m |
| 18 | + * @param {number} k |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var countGoodArrays = function(n, m, k) { |
| 22 | + const MOD = 1e9 + 7; |
| 23 | + |
| 24 | + if (m === 1) { |
| 25 | + return k === n - 1 ? 1 : 0; |
| 26 | + } |
| 27 | + |
| 28 | + const choose = binomialCoeff(n - 1, k); |
| 29 | + const power = modPow(m - 1, n - 1 - k, MOD); |
| 30 | + const result = Number((BigInt(choose) * BigInt(m) * BigInt(power)) % BigInt(MOD)); |
| 31 | + |
| 32 | + return result; |
| 33 | + |
| 34 | + function modPow(base, exp, mod) { |
| 35 | + let result = 1n; |
| 36 | + base = ((BigInt(base) % BigInt(mod)) + BigInt(mod)) % BigInt(mod); |
| 37 | + exp = BigInt(exp); |
| 38 | + mod = BigInt(mod); |
| 39 | + |
| 40 | + while (exp > 0n) { |
| 41 | + if (exp & 1n) result = (result * base) % mod; |
| 42 | + base = (base * base) % mod; |
| 43 | + exp >>= 1n; |
| 44 | + } |
| 45 | + return Number(result); |
| 46 | + } |
| 47 | + |
| 48 | + function modInverse(a, mod) { |
| 49 | + return modPow(a, mod - 2, mod); |
| 50 | + } |
| 51 | + |
| 52 | + function binomialCoeff(n, k) { |
| 53 | + if (k > n || k < 0) return 0; |
| 54 | + if (k === 0 || k === n) return 1; |
| 55 | + |
| 56 | + if (k > n - k) k = n - k; |
| 57 | + |
| 58 | + let numerator = 1n; |
| 59 | + let denominator = 1n; |
| 60 | + |
| 61 | + for (let i = 0; i < k; i++) { |
| 62 | + numerator = (numerator * BigInt(n - i)) % BigInt(MOD); |
| 63 | + denominator = (denominator * BigInt(i + 1)) % BigInt(MOD); |
| 64 | + } |
| 65 | + |
| 66 | + const invDenom = modInverse(Number(denominator), MOD); |
| 67 | + return Number((numerator * BigInt(invDenom)) % BigInt(MOD)); |
| 68 | + } |
| 69 | +}; |
0 commit comments