Given an array arr[] consisting of N integers, and an integer K, the task is to find the maximum number of inversions of the given array possible after the removal of K array elements.
Examples:
Input: arr[] = {2, 3, 4, 1}, K = 2
Output: 1
Explanation: Removing the 1st and 2nd array elements modifies the array to {4, 1}. Therefore, the maximum number of inversions is 1.Input: arr[] = {4, 3, 2, 1}, K = 3
Output: 0
Explanation: Since the array after K removals will have only 1 element remaining, the maximum number of inversions is 0.
Approach: Follow the steps below to solve the problem:
- Initialize a variable res to store the maximum number of inversions after removing K elements from the array arr[].
- Initialize a binary string S of length N to store which (N – K) elements to be considered from the array arr[].
- Store 0 at [0, K – 1] positions which denote K removed elements, and 1 at [K, N – 1] positions which denote (N – K) selected elements in string S.
- Generate all permutations of string S and do the following:
- Initialize an array v to store the (N – K) selected elements from arr[] in accordance with string S.
- Count the number of inversions in array v and store in cnt.
- Update the res to a maximum of res and cnt.
- After the above steps, print the value of res as the resultant.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to find the maximum number // of inversions after K removals void maximizeInversions( int a[], int n,                         int k) {     // Initialize a binary string     string s; Â
    // Iterate over range [0, K]     for ( int i = 0; i < k; i++)     { Â
        // Append 0 to the string         s += "0" ;     } Â
    for ( int i = k; i < n; i++)     { Â
        // Append 1 to the string         s += "1" ;     } Â
    // Stores the maximum number of     // inversions after K removals     int res = 0; Â
    // Generate all permutations     // of string s     do     { Â
        // Stores the current array         vector< int > v; Â
        // Stores number of inversions         // of the current array         int cnt = 0; Â
        for ( int i = 0; i < n; i++)         {             if (s[i] == '1' )                 v.push_back(a[i]);         } Â
        // Find the number of inversions         // in the array v         for ( int i = 0;              i < v.size() - 1; i++)         { Â
            for ( int j = i + 1;                  j < v.size(); j++)             { Â
                // Condition to check if the                 // number of pairs satisfy                 // required condition                 if (v[i] >= v[j]) Â
                    // Increment the count                     cnt++;             }         } Â
        // Update res         res = max(res, cnt); Â
    }   while (next_permutation(s.begin(),                               s.end())); Â
    // Print the result     cout << res; } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 2, 3, 4, 1 }; Â Â Â Â int N = sizeof (arr) / sizeof (arr[0]); Â Â Â Â int K = 2; Â
    // Function Call     maximizeInversions(arr, N, K); Â
    return 0; } |
Java
// Java program for the above approach import java.util.*; Â
class GFG { Â
// Function to find the maximum number // of inversions after K removals static void maximizeInversions( int a[], int n,                                 int k) {     // Initialize a binary String     String s= "" ; Â
    // Iterate over range [0, K]     for ( int i = 0 ; i < k; i++)     { Â
        // Append 0 to the String         s += "0" ;     } Â
    for ( int i = k; i < n; i++)     { Â
        // Append 1 to the String         s += "1" ;     } Â
    // Stores the maximum number of     // inversions after K removals     int res = 0 ; Â
    // Generate all permutations     // of String s     do     { Â
        // Stores the current array         Vector<Integer> v = new Vector<>(); Â
        // Stores number of inversions         // of the current array         int cnt = 0 ; Â
        for ( int i = 0 ; i < n; i++)         {             if (s.charAt(i) == '1' )                 v.add(a[i]);         } Â
        // Find the number of inversions         // in the array v         for ( int i = 0 ;              i < v.size() - 1 ; i++)         { Â
            for ( int j = i + 1 ;                  j < v.size(); j++)             { Â
                // Condition to check if the                 // number of pairs satisfy                 // required condition                 if (v.get(i) >= v.get(j)) Â
                    // Increment the count                     cnt++;             }         } Â
        // Update res         res = Math.max(res, cnt); Â
    }   while (next_permutation(s)); Â
    // Print the result     System.out.print(res); } Â
static boolean next_permutation(String str) { Â Â Â Â char []p = str.toCharArray(); Â Â Â Â Â Â for ( int a = p.length - 2 ; a >= 0 ; --a) Â Â Â Â Â Â Â Â if (p[a] < p[a + 1 ]) Â Â Â Â Â Â Â Â Â Â for ( int b = p.length - 1 ;; --b) Â Â Â Â Â Â Â Â Â Â Â Â if (p[b] > p[a]) Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â char t = p[a]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[a] = p[b]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[b] = t; Â Â Â Â Â Â Â Â Â Â Â Â Â Â for (++a, b = p.length - 1 ; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â a < b; ++a, --b) Â Â Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â t = p[a]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[a] = p[b]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[b] = t; Â Â Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â Â Â Â Â Â Â return false ; Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â return true ; } Â
// Driver Code public static void main(String[] args) { Â Â Â Â int arr[] = { 2 , 3 , 4 , 1 }; Â Â Â Â int N = arr.length; Â Â Â Â int K = 2 ; Â
    // Function Call     maximizeInversions(arr, N, K); } } Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program for the above approach def next_permutation( Str ):          p = list ( Str )          for a in range ( len (p) - 2 , - 1 , - 1 ):         if p[a] < p[a + 1 ]:             b = len (p) - 1                          while True :                 if p[b] > p[a]:                     t = p[a]                     p[a] = p[b]                     p[b] = t                     a + = 1                     b = len (p) - 1                                          while a < b:                         t = p[a]                         p[a] = p[b]                         p[b] = t                         a + = 1                         b - = 1                                              return False                                      b - = 1                      return True Â
# Function to find the maximum number # of inversions after K removals def maximizeInversions(a, n, k):          # Initialize a binary string     s = "" Â
    # Iterate over range [0, K]     for i in range (k):                  # Append 0 to the string         s + = "0" Â
    for i in range (k, n):                  # Append 1 to the string         s + = "1" Â
    # Stores the maximum number of     # inversions after K removals     res = 0 Â
    # Generate all permutations     # of string s     while ( True ):                  # Stores the current array         v = [] Â
        # Stores number of inversions         # of the current array         cnt = 0 Â
        for i in range (n):             if (s[i] = = '1' ):                 v.append(a[i])                          # Find the number of inversions         # in the array v         for i in range ( len (v) - 1 ):             for j in range (i + 1 , len (v)):                                  # Condition to check if the                 # number of pairs satisfy                 # required condition                 if (v[i] > = v[j]): Â
                    # Increment the count                     cnt + = 1 Â
        # Update res         res = max (res, cnt)                  if ( not next_permutation(s)):             break Â
    # Print the result     print (res) Â
# Driver Code arr = [ 2 , 3 , 4 , 1 ] N = len (arr) K = 2 Â
# Function Call maximizeInversions(arr, N, K) Â
# This code is contributed by divyeshrabadiya07 |
C#
// C# program for the above approach using System; using System.Collections.Generic; Â
class GFG { Â
// Function to find the maximum number // of inversions after K removals static void maximizeInversions( int []a, int n,                                 int k) {     // Initialize a binary String     String s= "" ; Â
    // Iterate over range [0, K]     for ( int i = 0; i < k; i++)     { Â
        // Append 0 to the String         s += "0" ;     } Â
    for ( int i = k; i < n; i++)     { Â
        // Append 1 to the String         s += "1" ;     } Â
    // Stores the maximum number of     // inversions after K removals     int res = 0; Â
    // Generate all permutations     // of String s     do     { Â
        // Stores the current array         List< int > v = new List< int >(); Â
        // Stores number of inversions         // of the current array         int cnt = 0; Â
        for ( int i = 0; i < n; i++)         {             if (s[i] == '1' )                 v.Add(a[i]);         } Â
        // Find the number of inversions         // in the array v         for ( int i = 0;              i < v.Count - 1; i++)         { Â
            for ( int j = i + 1;                  j < v.Count; j++)             { Â
                // Condition to check if the                 // number of pairs satisfy                 // required condition                 if (v[i] >= v[j]) Â
                    // Increment the count                     cnt++;             }         } Â
        // Update res         res = Math.Max(res, cnt); Â
    }   while (next_permutation(s)); Â
    // Print the result     Console.Write(res); } Â
static bool next_permutation(String str) { Â Â Â Â char []p = str.ToCharArray(); Â Â Â Â Â Â for ( int a = p.Length - 2; a >= 0; --a) Â Â Â Â Â Â Â Â if (p[a] < p[a + 1]) Â Â Â Â Â Â Â Â Â Â for ( int b = p.Length - 1;; --b) Â Â Â Â Â Â Â Â Â Â Â Â if (p[b] > p[a]) Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â char t = p[a]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[a] = p[b]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[b] = t; Â Â Â Â Â Â Â Â Â Â Â Â Â Â for (++a, b = p.Length - 1; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â a < b; ++a, --b) Â Â Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â t = p[a]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[a] = p[b]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â p[b] = t; Â Â Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â Â Â Â Â Â Â return false ; Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â return true ; } Â
// Driver Code public static void Main(String[] args) { Â Â Â Â int []arr = { 2, 3, 4, 1 }; Â Â Â Â int N = arr.Length; Â Â Â Â int K = 2; Â
    // Function Call     maximizeInversions(arr, N, K); } } Â
// This code contributed by Princi Singh |
Javascript
<script> Â
// JavaScript program for the above approach Â
// Function to find the maximum number // of inversions after K removals function maximizeInversions(a, n, k) {     // Initialize a binary String     let s= "" ; Â
    // Iterate over range [0, K]     for (let i = 0; i < k; i++)     { Â
        // Append 0 to the String         s += "0" ;     } Â
    for (let i = k; i < n; i++)     { Â
        // Append 1 to the String         s += "1" ;     } Â
    // Stores the maximum number of     // inversions after K removals     let res = 0; Â
    // Generate all permutations     // of String s     do     { Â
        // Stores the current array         let v = []; Â
        // Stores number of inversions         // of the current array         let cnt = 0; Â
        for (let i = 0; i < n; i++)         {             if (s[i] == '1' )                 v.push(a[i]);         } Â
        // Find the number of inversions         // in the array v         for (let i = 0;              i < v.length - 1; i++)         { Â
            for (let j = i + 1;                  j < v.length; j++)             { Â
                // Condition to check if the                 // number of pairs satisfy                 // required condition                 if (v[i] >= v[j]) Â
                    // Increment the count                     cnt++;             }         } Â
        // Update res         res = Math.max(res, cnt); Â
    }     while (next_permutation(s)); Â
    // Print the result     document.write(res); } Â
function next_permutation(str) { Â Â Â Â Â Â for (let a = str.length - 2; a >= 0; --a) Â Â Â Â Â Â Â Â if (str[a] < str[a + 1]) Â Â Â Â Â Â Â Â Â Â for (let b = str.length - 1;; --b) Â Â Â Â Â Â Â Â Â Â Â Â if (str[b] > str[a]) Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â let t = str[a]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â str[a] = str[b]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â str[b] = t; Â Â Â Â Â Â Â Â Â Â Â Â Â Â for (++a, b = str.length - 1; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â a < b; ++a, --b) Â Â Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â t = str[a]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â str[a] = str[b]; Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â str[b] = t; Â Â Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â Â Â Â Â Â Â return false ; Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â return true ; } Â
// Driver Code Â
    let arr = [ 2, 3, 4, 1 ];     let N = arr.length;     let K = 2; Â
    // Function Call     maximizeInversions(arr, N, K);          // This code is contributed by Dharanendra L V.      </script> |
1
Â
Time Complexity: O((N!)*(N – K)2)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!