3405. Count the Number of Arrays with K Matching Adjacent Elements
You are given three integers
n,m,k. A good arrayarrof sizenis defined as follows:
- Each element in
arris in the inclusive range[1, m].- Exactly
kindicesi(where1 <= i < n) satisfy the conditionarr[i - 1] == arr[i].Return the number of good arrays that can be formed.
Since the answer may be very large, return it modulo
109 + 7.Example 1:
Input: n = 3, m = 2, k = 1
Output: 4
Explanation:
- There are 4 good arrays. They are
[1, 1, 2],[1, 2, 2],[2, 1, 1]and[2, 2, 1].- Hence, the answer is 4.
Example 2:
Input: n = 4, m = 2, k = 2
Output: 6
Explanation:
- The good arrays are
[1, 1, 1, 2],[1, 1, 2, 2],[1, 2, 2, 2],[2, 1, 1, 1],[2, 2, 1, 1]and[2, 2, 2, 1].- Hence, the answer is 6.
Example 3:
Input: n = 5, m = 2, k = 0
Output: 2
Explanation:
- The good arrays are
[1, 2, 1, 2, 1]and[2, 1, 2, 1, 2]. Hence, the answer is 2.
MOD = 10**9 + 7
MX = 10**5
fact = [0] * MX
inv_fact = [0] * MX
def qpow(x, n):
res = 1
while n:
if n & 1:
res = res * x % MOD
x = x * x % MOD
n >>= 1
return res
def init():
if fact[0] != 0:
return
fact[0] = 1
for i in range(1, MX):
fact[i] = fact[i - 1] * i % MOD
inv_fact[MX - 1] = qpow(fact[MX - 1], MOD - 2)
for i in range(MX - 1, 0, -1):
inv_fact[i - 1] = inv_fact[i] * i % MOD
def comb(n, m):
return fact[n] * inv_fact[m] % MOD * inv_fact[n - m] % MOD
class Solution:
def countGoodArrays(self, n: int, m: int, k: int) -> int:
init()
return comb(n - 1, k) * m % MOD * qpow(m - 1, n - k - 1) % MOD