Find the Number of K-Even Arrays Problem
Description
LeetCode Problem 3339.
You are given three integers n, m, and k.
An array arr is called k-even if there are exactly k indices such that, for each of these indices i (0 <= i < n - 1):
(arr[i] * arr[i + 1]) - arr[i] - arr[i + 1]is even.
Return the number of possible k-even arrays of size n where all elements are in the range [1, m].
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: n = 3, m = 4, k = 2
Output: 8
Explanation:
The 8 possible 2-even arrays are:
- [2, 2, 2]
- [2, 2, 4]
- [2, 4, 2]
- [2, 4, 4]
- [4, 2, 2]
- [4, 2, 4]
- [4, 4, 2]
- [4, 4, 4]
Example 2:
Input: n = 5, m = 1, k = 0
Output: 1
Explanation:
The only 0-even array is [1, 1, 1, 1, 1].
Example 3:
Input: n = 7, m = 7, k = 5
Output: 5832
Constraints:
1 <= n <= 7500 <= k <= n - 11 <= m <= 1000
Solution
Approach: Memoized search
In [1, m] there are cnt0 = m / 2 even and cnt1 = m - cnt0 odd numbers. Fill the array from left to right and track the position i, the number of "good" adjacent pairs still needed j, and the parity k of the previous element (the first element has no previous one, so start with k = 1, which makes no pair counted).
Placing an odd number gives cnt1 choices and never creates a counted pair, so go to (i + 1, j, 1). Placing an even number gives cnt0 choices and creates a counted pair exactly when the previous element is odd, so go to (i + 1, j - (previous was odd), 0). If j drops below 0 the branch is invalid, and when all n positions are filled the branch counts only if j == 0. The answer is dfs(0, k, 1).
Complexity: O(n * k) time and O(n * k) space.
from functools import lru_cache
class Solution:
def countOfArrays(self, n: int, m: int, k: int) -> int:
@lru_cache(None)
def dfs(i: int, j: int, k: int) -> int:
if j < 0:
return 0
if i >= n:
return int(j == 0)
return (
cnt1 * dfs(i + 1, j, 1) + cnt0 * dfs(i + 1, j - (k & 1 ^ 1), 0)
) % mod
cnt0 = m // 2
cnt1 = m - cnt0
mod = 10**9 + 7
ans = dfs(0, k, 1)
dfs.cache_clear()
return ans