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 ; Driver Code ; Given N and K ; Function Call
def numberOfPermWithKInversion ( N , K ) : NEW_LINE INDENT dp = [ [ 0 ] * ( K + 1 ) ] * 2 NEW_LINE mod = 1000000007 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 0 , K + 1 ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT dp [ i % 2 ] [ j ] = 1 if ( j == 0 ) else 0 NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT dp [ i % 2 ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT var = ( 0 if ( max ( j - ( i - 1 ) , 0 ) == 0 ) else dp [ 1 - i % 2 ] [ max ( j - ( i - 1 ) , 0 ) - 1 ] ) NEW_LINE dp [ i % 2 ] [ j ] = ( ( dp [ i % 2 ] [ j - 1 ] % mod + ( dp [ 1 - i % 2 ] [ j ] - ( var ) + mod ) % mod ) % mod ) NEW_LINE DEDENT DEDENT DEDENT print ( dp [ N % 2 ] [ K ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 2 NEW_LINE numberOfPermWithKInversion ( N , K ) NEW_LINE DEDENT