Count inversions in a sequence generated by appending given array K times | Function to count the number of inversions in K copies of given array ; Stores count of inversions in the given array ; Stores the count of pairs of distinct array elements ; Traverse the array ; Generate each pair ; Check for each pair , if the condition is satisfied or not ; If pairs consist of distinct elements ; Count inversiosn in the sequence ; Print the answer ; Given array ; Given K ; Size of the array
function totalInversions ( arr , K , N ) { let inv = 0 ; let X = 0 ; let i , j ; for ( i = 0 ; i < N ; i ++ ) { for ( j = 0 ; j < N ; j ++ ) { if ( arr [ i ] > arr [ j ] && i < j ) inv ++ ; if ( arr [ i ] > arr [ j ] ) X ++ ; } } let totalInv = X * K * ( K - 1 ) / 2 + inv * K ; document . write ( totalInv ) ; } let arr = [ 2 , 1 , 3 ] ; let K = 3 ; let N = arr . length ; totalInversions ( arr , K , N ) ;