Find the Number of K-Even Arrays - Problem
You're tasked with counting special arrays based on a unique mathematical property! Given three integers n (array size), m (maximum value), and k (target count), you need to find how many arrays of size n have exactly k "magic pairs".
A magic pair occurs at index i when the expression (arr[i] * arr[i+1]) - arr[i] - arr[i+1] evaluates to an even number. All array elements must be in the range [1, m].
Goal: Count all possible k-even arrays and return the result modulo 10^9 + 7.
Example: For array [2, 3, 1], check pairs: (2*3) - 2 - 3 = 1 (odd), (3*1) - 3 - 1 = -1 (odd). This array has 0 magic pairs.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 3, m = 2, k = 1
โบ
Output:
4
๐ก Note:
Arrays with exactly 1 magic pair: [1,1,2], [2,2,1], [1,2,2], [2,1,1]. Magic pairs occur when both numbers have same parity (both odd or both even).
example_2.py โ No Magic Pairs
$
Input:
n = 2, m = 3, k = 0
โบ
Output:
6
๐ก Note:
Arrays with 0 magic pairs: [1,2], [1,3], [2,1], [2,3], [3,1], [3,2]. All pairs have different parity (one odd, one even).
example_3.py โ Edge Case
$
Input:
n = 1, m = 5, k = 0
โบ
Output:
5
๐ก Note:
Single element arrays have no adjacent pairs, so k must be 0. All 5 possible arrays [1], [2], [3], [4], [5] are valid.
Constraints
- 1 โค n โค 1000
- 1 โค m โค 1000
- 0 โค k โค n-1
- Answer must be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
State Definition
dp[position][last_parity][magic_count] = number of ways
2
Transition Logic
For each new number, check if it creates a magic pair with previous
3
Parity Check
Magic pair formed when both numbers odd or both even
4
Final Count
Sum all states with exactly k magic pairs
Key Takeaway
๐ฏ Key Insight: Use DP to track position, last element's parity, and magic pair count. Magic pairs form when adjacent elements have same parity, making this a manageable state space of O(n*2*k).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code