VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-inversions-possible-after-exactly-k-removals-from-given-array/

⇱ Maximum inversions possible after exactly K removals from given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum inversions possible after exactly K removals from given array

Last Updated : 23 Jul, 2025

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:


Output: 
1

 

Time Complexity: O((N!)*(N - K)2)
Auxiliary Space: O(N)


 

Comment