Skip to content
Related Articles

Related Articles

Minimize count of array elements to be removed such that at least K elements are equal to their index values

Improve Article
Save Article
  • Last Updated : 06 Oct, 2021
Improve Article
Save Article

Given an array arr[](1- based indexing) consisting of N integers and a positive integer K, the task is to find the minimum number of array elements that must be removed such that at least K array elements are equal to their index values. If it is not possible to do so, then print -1.

Examples:

Input: arr[] = {5, 1, 3, 2, 3}  K = 2
Output:
Explanation:
Following are the removal operations required:

  • Removing arr[1] modifies array to {1, 3, 2, 3} -> 1 element is equal to its index value.
  • Removing arr[3] modifies array to {1, 2, 3} -> 3 elements are equal to their index value.

After the above operations 3(>= K) elements are equal to their index values and the minimum removals required is 2.

Input: arr[] = {2, 3, 4}  K = 1
Output: -1 

Approach: The above problem can be solved with the help of Dynamic Programming. Follow the steps below to solve the given problem.

  • Initialize a 2-D dp table such that dp[i][j] will denote maximum elements that have values equal to their indexes when a total of j elements are present.
  • All the values in the dp table are initially filled with 0s.
  • Iterate for each i in the range [0, N-1] and j in the range [0, i], there are two choices.
    • Delete the current element, the dp table can be updated as dp[i+1][j] = max(dp[i+1][j], dp[i][j]).
    • Keep the current element, then dp table can be updated as: dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j] + (arr[i+1] == j+1)).
  • Now for each j in the range [N, 0] check if the value of dp[N][j] is greater than or equal to K. Take minimum if found and return the answer.
  • Otherwise, return -1 at the end. That means no possible answer is found.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to minimize the removals of
// array elements such that atleast K
// elements are equal to their indices
int MinimumRemovals(int a[], int N, int K)
{
    // Store the array as 1-based indexing
    // Copy of first array
    int b[N + 1];
    for (int i = 0; i < N; i++) {
        b[i + 1] = a[i];
    }
 
    // Make a dp-table of (N*N) size
    int dp[N + 1][N + 1];
 
    // Fill the dp-table with zeroes
    memset(dp, 0, sizeof(dp));
    for (int i = 0; i < N; i++) {
        for (int j = 0; j <= i; j++) {
 
            // Delete the current element
            dp[i + 1][j] = max(
                dp[i + 1][j], dp[i][j]);
 
            // Take the current element
            dp[i + 1][j + 1] = max(
                dp[i + 1][j + 1],
                dp[i][j] + ((b[i + 1] == j + 1) ? 1 : 0));
        }
    }
 
    // Check for the minimum removals
    for (int j = N; j >= 0; j--) {
        if (dp[N][j] >= K) {
            return (N - j);
        }
    }
    return -1;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 1, 3, 2, 3 };
    int K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << MinimumRemovals(arr, N, K);
 
    return 0;
}

Java




// Java program for the above approach
 
import java.io.*;
 
class GFG {
 
    // Function to minimize the removals of
    // array elements such that atleast K
    // elements are equal to their indices
    static int MinimumRemovals(int a[], int N, int K)
    {
        // Store the array as 1-based indexing
        // Copy of first array
        int b[] = new int[N + 1];
        for (int i = 0; i < N; i++) {
            b[i + 1] = a[i];
        }
 
        // Make a dp-table of (N*N) size
        int dp[][] = new int[N + 1][N + 1];
 
        for (int i = 0; i < N; i++) {
            for (int j = 0; j <= i; j++) {
 
                // Delete the current element
                dp[i + 1][j] = Math.max(dp[i + 1][j], dp[i][j]);
 
                // Take the current element
                dp[i + 1][j + 1] = Math.max(
                    dp[i + 1][j + 1],
                    dp[i][j]
                        + ((b[i + 1] == j + 1) ? 1 : 0));
            }
        }
 
        // Check for the minimum removals
        for (int j = N; j >= 0; j--) {
            if (dp[N][j] >= K) {
                return (N - j);
            }
        }
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 5, 1, 3, 2, 3 };
        int K = 2;
        int N = arr.length;
        System.out.println(MinimumRemovals(arr, N, K));
    }
}
 
// This code is contributed by Dharanendra L V.

Python3




# Python 3 program for the above approach
 
# Function to minimize the removals of
# array elements such that atleast K
# elements are equal to their indices
def MinimumRemovals(a, N, K):
   
    # Store the array as 1-based indexing
    # Copy of first array
    b = [0 for i in range(N + 1)]
    for i in range(N):
        b[i + 1] = a[i]
 
    # Make a dp-table of (N*N) size
    dp = [[0 for i in range(N+1)] for j in range(N+1)]
 
    for i in range(N):
        for j in range(i + 1):
           
            # Delete the current element
            dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
 
            # Take the current element
            dp[i + 1][j + 1] = max(dp[i + 1][j + 1],dp[i][j] + (1 if (b[i + 1] == j + 1) else 0))
 
    # Check for the minimum removals
    j = N
    while(j >= 0):
        if(dp[N][j] >= K):
            return (N - j)
        j -= 1
    return -1
 
# Driver Code
if __name__ == '__main__':
    arr = [5, 1, 3, 2, 3]
    K = 2
    N = len(arr)
    print(MinimumRemovals(arr, N, K))
     
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# code for the above approach
using System;
 
public class GFG
{
   
    // Function to minimize the removals of
    // array elements such that atleast K
    // elements are equal to their indices
    static int MinimumRemovals(int[] a, int N, int K)
    {
       
        // Store the array as 1-based indexing
        // Copy of first array
        int[] b = new int[N + 1];
        for (int i = 0; i < N; i++) {
            b[i + 1] = a[i];
        }
 
        // Make a dp-table of (N*N) size
        int[, ] dp = new int[N + 1, N + 1];
 
        for (int i = 0; i < N; i++) {
            for (int j = 0; j <= i; j++) {
 
                // Delete the current element
                dp[i + 1, j]
                    = Math.Max(dp[i + 1, j], dp[i, j]);
 
                // Take the current element
                dp[i + 1, j + 1] = Math.Max(
                    dp[i + 1, j + 1],
                    dp[i, j]
                        + ((b[i + 1] == j + 1) ? 1 : 0));
            }
        }
 
        // Check for the minimum removals
        for (int j = N; j >= 0; j--) {
            if (dp[N, j] >= K) {
                return (N - j);
            }
        }
        return -1;
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 5, 1, 3, 2, 3 };
        int K = 2;
        int N = arr.Length;
        Console.Write(MinimumRemovals(arr, N, K));
    }
}
 
// This code is contributed by Potta Lokesh

Javascript




<script>
// Javascript program for the above approach
 
// Function to minimize the removals of
// array elements such that atleast K
// elements are equal to their indices
function MinimumRemovals(a, N, K)
{
 
    // Store the array as 1-based indexing
    // Copy of first array
    let b = new Array(N + 1);
    for (let i = 0; i < N; i++) {
        b[i + 1] = a[i];
    }
 
    // Make a dp-table of (N*N) size
    let dp = new Array(N + 1).fill(0).map(() => new Array(N + 1).fill(0));
 
    for (let i = 0; i < N; i++) {
        for (let j = 0; j <= i; j++) {
 
            // Delete the current element
            dp[i + 1][j] = Math.max(
                dp[i + 1][j], dp[i][j]);
 
            // Take the current element
            dp[i + 1][j + 1] = Math.max(
                dp[i + 1][j + 1],
                dp[i][j] + ((b[i + 1] == j + 1) ? 1 : 0));
        }
    }
 
    // Check for the minimum removals
    for (let j = N; j >= 0; j--) {
        if (dp[N][j] >= K) {
            return (N - j);
        }
    }
    return -1;
}
 
// Driver Code
 
    let arr = [ 5, 1, 3, 2, 3 ];
    let K = 2;
    let N = arr.length
    document.write(MinimumRemovals(arr, N, K));
     
    // This code is contributed by _saurabh_jaiswal.
</script>

 
 

Output: 

2

 

 

Time Complexity: O(N2)
Auxiliary Space: O(N2)

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!