Problem Description
You are given three integers n, m, k. A good array arr of size n is defined as follows:
- Each element in arr is in the inclusive range [1, m].
- Exactly 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 10^9 + 7.
Key Insights
- The problem involves combinatorial counting based on the arrangement of elements and their repetitions.
- We need to account for the number of ways to choose the positions of the matching elements and the non-matching elements.
- The transition between matching and non-matching elements can be represented using combinatorial methods.
- Pre-computation of factorials and modular inverses can help compute combinations efficiently.
Space and Time Complexity
Time Complexity: O(n) for pre-computation and O(1) for each query. Space Complexity: O(n) for storing factorials and inverses.
Solution
To solve this problem, we can use a combinatorial approach. The main idea is to compute:
- The total ways to choose k matching pairs from n-1 possible positions.
- The arrangements of distinct elements in non-matching positions.
- Combine these counts to get the total number of valid arrays.
We will use dynamic programming or combinatorial formulae to compute factorials and their inverses for efficient combination calculations.