Count inversions in a sequence generated by appending given array K times | Java program for the above approach ; 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 ; Driver Code ; Given array ; Given K ; Size of the array
import java . util . * ; class GFG { static void totalInversions ( int arr [ ] , int K , int N ) { int inv = 0 ; int X = 0 ; int 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 ++ ; } } int totalInv = X * K * ( K - 1 ) / 2 + inv * K ; System . out . println ( totalInv ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 1 , 3 } ; int K = 3 ; int N = arr . length ; totalInversions ( arr , K , N ) ; } }