Problem Description
Given integers n, m, and k, count the number of arrays arr of size n (with each element from 1 to m) that are called k-even. An array is k-even if exactly k indices i (0 ≤ i < n - 1) satisfy that (arr[i] * arr[i+1]) - arr[i] - arr[i+1] is even. Return the answer modulo 10^9 + 7.
Key Insights
- The expression (a * b) - a - b simplifies algebraically to (a-1)*(b-1) - 1.
- Analyzing the parity, the expression is even if and only if both a and b are even.
- Count the number of evens (e) and odds (o) in [1, m]. Then the problem reduces to counting arrays with exactly k occurrences where two consecutive elements are even.
- A dynamic programming (DP) approach can track the number of arrays built so far along with the last element’s parity.
Space and Time Complexity
Time Complexity: O(n * k)
Space Complexity: O(n * k) [can be optimized to O(k)]
Solution
We use DP with state dp[i][j][p] where:
- i is the current length of the array.
- j is the number of pairs of consecutive even numbers seen so far.
- p indicates the parity of the last element (0 for odd, 1 for even).
Initialization:
- For the first element, dp[1][0][0] = o (number of odds) and dp[1][0][1] = e (number of evens).
Transitions:
- When adding an odd number:
- The parity does not contribute a new even-even pair.
- dp[i][j][0] += (dp[i-1][j][0] + dp[i-1][j][1]) * o.
- When adding an even number:
- If the previous number was even, it forms an even-even pair. Thus, dp[i][j][1] gets contribution from dp[i-1][j-1][1] * e.
- If the previous number was odd, no new even-even pair is added so: dp[i][j][1] += dp[i-1][j][0] * e.
The final answer is the sum dp[n][k][0] + dp[n][k][1] modulo 10^9+7.