Hard
You are given three integers n
, m
, k
. A good array arr
of size n
is defined as follows:
arr
is in the inclusive range [1, m]
.k
indices i
(where 1 <= i < n
) satisfy the condition arr[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:
[1, 1, 2]
, [1, 2, 2]
, [2, 1, 1]
and [2, 2, 1]
.Example 2:
Input: n = 4, m = 2, k = 2
Output: 6
Explanation:
[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]
.Example 3:
Input: n = 5, m = 2, k = 0
Output: 2
Explanation:
[1, 2, 1, 2, 1]
and [2, 1, 2, 1, 2]
. Hence, the answer is 2.Constraints:
1 <= n <= 105
1 <= m <= 105
0 <= k <= n - 1
public class Solution {
private static final int MOD = (int) (1e9 + 7);
public int countGoodArrays(int n, int m, int k) {
long[] f = new long[n + 1];
f[0] = 1;
f[1] = 1;
for (int i = 2; i < f.length; i++) {
f[i] = (f[i - 1] * i % MOD);
}
long ans = comb(n - 1, k, f);
ans = ans * m % MOD;
ans = ans * ex(m - 1L, n - k - 1L) % MOD;
return (int) ans;
}
private long ex(long b, long e) {
long ans = 1;
while (e > 0) {
if (e % 2 == 1) {
ans = (ans * b) % MOD;
}
b = (b * b) % MOD;
e = e >> 1;
}
return ans;
}
private long comb(int n, int r, long[] f) {
return f[n] * (ff(f[r])) % MOD * ff(f[n - r]) % MOD;
}
private long ff(long x) {
return ex(x, MOD - 2L);
}
}