Problem Description
Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. An inverse pair is defined as a pair of indices [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j]. Since the answer can be large, return it modulo 10^9 + 7.
Key Insights
- The problem can be solved using dynamic programming.
- The number of inverse pairs increases with the arrangement of numbers.
- A 2D DP table can be utilized where dp[i][j] represents the number of arrays of size i with exactly j inverse pairs.
- The transition involves calculating the number of ways to form arrays by considering the current number's position and the previously computed states.
Space and Time Complexity
Time Complexity: O(n * k^2)
Space Complexity: O(n * k)
Solution
To solve the problem, we will use a dynamic programming approach. We create a 2D array dp
where dp[i][j]
denotes the number of arrays of length i
with exactly j
inverse pairs.
- Initialize the base case: An array of length 0 has exactly 0 inverse pairs, so
dp[0][0] = 1
. - For each length
i
from 1 ton
, compute the number of inverse pairsj
from 0 tok
. - The value of
dp[i][j]
can be constructed by summing values from previous lengths considering how the current number can contribute to the inverse pairs. - Specifically, we can use the relationship:
dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][j-i]
This means that we can form an array of lengthi
by adding the current number to previous arrays of lengthi-1
, and we need to account for how many new inverse pairs are created depending on the position of the current number.
- Finally, return
dp[n][k] % (10^9 + 7)
.