K Inverse Pairs Array - Problem
Imagine you're arranging numbers from
1 to n in a specific way to create exactly k inverse pairs. An inverse pair occurs when a larger number appears before a smaller number in the array - like having 3 before 1 in [3, 2, 1].
Your Challenge: Given two integers n and k, determine how many different arrays can be formed using numbers 1 to n such that there are exactly k inverse pairs.
For example, with n=3 and k=1, the arrays [1,3,2], [2,1,3], and [3,1,2] each have exactly one inverse pair. Since the result can be enormous, return it modulo 109 + 7. Input & Output
example_1.py โ Basic case with small numbers
$
Input:
n = 3, k = 0
โบ
Output:
1
๐ก Note:
Only the array [1,2,3] has exactly 0 inverse pairs (it's already sorted)
example_2.py โ Multiple valid arrangements
$
Input:
n = 3, k = 1
โบ
Output:
2
๐ก Note:
Arrays [1,3,2], [2,1,3] each have exactly 1 inverse pair: (3,2) and (2,1) respectively
example_3.py โ Maximum inversions case
$
Input:
n = 4, k = 6
โบ
Output:
1
๐ก Note:
Only [4,3,2,1] has the maximum 6 inverse pairs: (4,3), (4,2), (4,1), (3,2), (3,1), (2,1)
Constraints
- 1 โค n โค 1000
- 0 โค k โค 1000
- Maximum possible inverse pairs for n numbers is nร(n-1)/2
- Result must be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Understand Inverse Pairs
An inverse pair (i,j) means arr[i] > arr[j] but i < j - larger number appears before smaller
2
Recursive Structure
When placing largest number n at position i, it creates i inverse pairs with all previous smaller numbers
3
DP Transition
dp[n][k] = sum of dp[n-1][k-i] for i from 0 to min(k, n-1)
4
Optimization
Use prefix sum to compute each dp[i][j] in O(1) instead of O(k) time
Key Takeaway
๐ฏ Key Insight: When placing the largest number n, its position determines exactly how many new inverse pairs are created, allowing us to break down the problem recursively and solve it efficiently with dynamic programming.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code