Problem Description
Given two integers n and k, count the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs (an inverse pair is a pair of indices [i, j] where 0 <= i < j < n and nums[i] > nums[j]). Since the answer can be huge, return it modulo 10^9 + 7.
Key Insights
- Understand that an inverse pair is created when a larger number appears before a smaller number.
- Use dynamic programming considering the recurrence: dp[i][j] = sum(dp[i-1][j - r]) for r from 0 to min(j, i-1).
- Recognize that the naive DP transition can be optimized with prefix sums to reduce time complexity.
- Only the previous row of the DP table is needed at any time, enabling space optimization.
Space and Time Complexity
Time Complexity: O(n * k)
Space Complexity: O(k)
Solution
The solution leverages dynamic programming. Define dp[i][j] as the number of arrays using numbers 1 to i with exactly j inverse pairs. For a new number i, when inserted into every possible position of the array formed by numbers 1 to i-1, it creates different amounts of new inverse pairs depending on the insertion position. The recurrence relation is expressed as:
dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][j - (i-1)],
for valid indices, where dp[i-1][x] is considered 0 when x is negative.
To avoid recomputing the sum in the recurrence, we compute prefix sums over dp[i-1][:]. This turns the inner loop into an O(1) operation by subtracting the cumulative sum at j-i from the cumulative sum at j. Finally, each dp[i][j] calculation is taken modulo 10^9+7. This DP approach efficiently handles the constraints.