# K Inverse Pairs Array in C++

C++Server Side ProgrammingProgramming

Suppose we have two integers n and k, we have to find how many different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. The inverse pair is for ith and jth element in the array, if i < j and a[i] > a[j] it is called an inverse pair. Here the answer may be very large, the answer should be modulo $10^{9}$ + 7.

So if the input is like n = 3 and k = 1, then the output will be 2 as the arrays [1,3,2] and [2,1,3] will have only one inverse pairs.

To solve this, we will follow these steps −

• Define one 2D array dp of size (n + 1) x (k + 1)
• dp[0, 0] := 1
• for initialize i := 1, when i<= n, update (increase i by 1), do −
• dp[i, 0] := 1
• for initialize j := 1, when j <= k, update (increase j by 1), do −
• dp[i, j] := dp[i, j - 1] + dp[i – 1, j]
• dp[i, j] := dp[i, j] mod m
• if j >= i, then −
• dp[i, j] := (dp[i, j] - dp[i – 1, j - i] + m) mod m
• return dp[n, k]

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
const int m = 1e9 + 7;
class Solution {
public:
int kInversePairs(int n, int k) {
vector < vector <int> > dp(n + 1, vector <int>(k + 1));
dp[0][0] = 1;
for(int i = 1; i <= n; i++){
dp[i][0] = 1;
for(int j = 1; j <= k; j++){
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
dp[i][j] %= m;
if(j >= i){
dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + m) % m;
}
}
}
return dp[n][k];
}
};
main(){
Solution ob;
cout << (ob.kInversePairs(4,2));
}

## Input

4
2

## Output

5
Updated on 01-Jun-2020 11:47:00