629. K Inverse Pairs Array
Explanation
To solve this problem, we can use dynamic programming. We can define a 2D array dp
where dp[i][j]
represents the number of different arrays of size i
with j
inverse pairs. We can then iterate through each element in the array and calculate the number of inverse pairs it can form with the previous elements.
- Initialize a 2D array
dp
of size(n+1) x (k+1)
with all values set to 0 exceptdp[0][0] = 1
. - Iterate from
i = 1
ton
andj = 0
tok
: a. Calculatedp[i][j]
based on the formula:dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][j-i+1]
- Return
dp[n][k]
modulo10^9 + 7
.
Time Complexity: O(nk^2) Space Complexity: O(nk)
class Solution {
public int kInversePairs(int n, int k) {
int MOD = 1000000007;
int[][] dp = new int[n+1][k+1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
dp[i][0] = 1;
for (int j = 1; j <= k; j++) {
for (int p = 0; p <= Math.min(j, i-1); p++) {
dp[i][j] = (dp[i][j] + dp[i-1][j-p]) % MOD;
}
}
}
return dp[n][k];
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.