Number of permutation with K inversions | Set 2 | Function to count permutations with K inversions ; Store number of permutations with K inversions ; If N = 1 only 1 permutation with no inversion ; For K = 0 only 1 permutation with no inversion ; Otherwise Update each dp state as per the reccurrance relation formed ; Print final count ; Given N and K ; Function Call
function numberOfPermWithKInversion ( N , K ) { let dp = new Array ( 2 ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } let mod = 1000000007 ; for ( let i = 1 ; i <= N ; i ++ ) { for ( let j = 0 ; j <= K ; j ++ ) { if ( i == 1 ) { dp [ i % 2 ] [ j ] = ( j == 0 ) ? 1 : 0 ; } else if ( j == 0 ) dp [ i % 2 ] [ j ] = 1 ; else dp [ i % 2 ] [ j ] = ( dp [ i % 2 ] [ j - 1 ] % mod + ( dp [ 1 - i % 2 ] [ j ] - ( ( Math . max ( j - ( i - 1 ) , 0 ) == 0 ) ? 0 : dp [ 1 - i % 2 ] [ Math . max ( j - ( i - 1 ) , 0 ) - 1 ] ) + mod ) % mod ) % mod ; } } document . write ( dp [ N % 2 ] [ K ] ) ; } let N = 3 , K = 2 ; numberOfPermWithKInversion ( N , K ) ;