You are given three integers n, m, k. A good arrayarr of size n is defined as follows:
Each element in arr is in the inclusive range [1, m].
Exactlyk 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:
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.
Constraints:
1 <= n <= 105
1 <= m <= 105
0 <= k <= n - 1
Solutions
Solution 1: Combinatorics + Fast Power
For an array of length \(n\), there are \(n - 1\) pairs of adjacent elements. We need to select \(k\) of these \(n - 1\) adjacent pairs such that the two elements in each of these \(k\) pairs are equal, and the remaining \(n - 1 - k\) adjacent pairs have different elements.
This is equivalent to splitting the array \(n - 1 - k\) times, resulting in \(n - k\) segments, where all elements in each segment are equal. The number of ways to split is \(C_{n - 1}^{n - 1 - k} = C_{n - 1}^{k}\).
For the first segment, we can choose any element from \([1, m]\). For the remaining \(n - k - 1\) segments, we just need to ensure that the element in each segment is different from the previous segment, so each of these segments has \(m - 1\) choices. In total, there are \(m \times (m - 1)^{n - k - 1}\) ways to choose.
Combining the two parts above, we get the answer:
\[
C_{n - 1}^{k} \times m \times (m - 1)^{n - k - 1} \bmod (10^9 + 7)
\]
In the code implementation, we can precompute factorials and inverses, and use fast power to calculate combinations.
Ignoring the preprocessing time and space, the time complexity is \(O(\log (n - k))\), and the space complexity is \(O(1)\).