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: 2
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++ 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 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. |
# 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# 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 |
<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> |
2
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Efficient approach : Space optimization
In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.
Implementation steps:
- Create a 1D vector dp of size N+1 and initialize it with 0.
- Set a base case by initializing the values of DP .
- Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
- At last iterate over Dp and whenever dp[j] >= K return (N – j) .
Implementation:
#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];
}
// Initialize the dp-table with zeroes
int dp[N + 1];
memset (dp, 0, sizeof (dp));
// Iterate over the array and fill the dp-table
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j > 0; j--) {
dp[j] = max(dp[j], dp[j - 1] + ((b[i + 1] == j) ? 1 : 0));
}
}
// Check for the minimum removals
for ( int j = N; j >= 0; j--) {
if (dp[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;
} // this code is contributed by bhardwajji |
import java.util.Arrays;
public class MinimumRemovals {
// 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];
}
// Initialize the dp-table with zeroes
int dp[] = new int [N + 1 ];
Arrays.fill(dp, 0 );
// Iterate over the array and fill the dp-table
for ( int i = 0 ; i < N; i++) {
for ( int j = i + 1 ; j > 0 ; j--) {
dp[j] = Math.max(dp[j], dp[j - 1 ] + ((b[i + 1 ] == j) ? 1 : 0 ));
}
}
// Check for the minimum removals
for ( int j = N; j >= 0 ; j--) {
if (dp[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));
}
} |
# 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 ] * (N + 1 )
for i in range (N):
b[i + 1 ] = a[i]
# Initialize the dp-table with zeroes
dp = [ 0 ] * (N + 1 )
# Iterate over the array and fill the dp-table
for i in range (N):
for j in range (i + 1 , 0 , - 1 ):
dp[j] = max (dp[j], dp[j - 1 ] + ((b[i + 1 ] = = j)))
# Check for the minimum removals
for j in range (N, - 1 , - 1 ):
if dp[j] > = K:
return (N - j)
return - 1
# Driver Code arr = [ 5 , 1 , 3 , 2 , 3 ]
K = 2
N = len (arr)
print (MinimumRemovals(arr, N, K))
|
using System;
public class Program
{ // Function to minimize the removals of
// array elements such that atleast K
// elements are equal to their indices
public 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];
}
// Initialize the dp-table with zeroes
int [] dp = new int [N + 1];
Array.Fill(dp, 0);
// Iterate over the array and fill the dp-table
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j > 0; j--) {
dp[j] = Math.Max(
dp[j],
dp[j - 1] + ((b[i + 1] == j) ? 1 : 0));
}
}
// Check for the minimum removals
for ( int j = N; j >= 0; j--) {
if (dp[j] >= K) {
return (N - j);
}
}
return -1;
}
// Driver Code
public static void Main()
{
int [] arr = { 5, 1, 3, 2, 3 };
int K = 2;
int N = arr.Length;
Console.WriteLine(MinimumRemovals(arr, N, K));
}
} // This code is contributed by user_dtewbxkn77n |
function minimumRemovals(a, N, K) {
// Store the array as 1-based indexing
// Copy of the first array
let b = new Array(N + 1);
for (let i = 0; i < N; i++) {
b[i + 1] = a[i];
}
// Initialize the dp-table with zeroes
let dp = new Array(N + 1).fill(0);
// Iterate over the array and fill the dp-table
for (let i = 0; i < N; i++) {
for (let j = i + 1; j > 0; j--) {
dp[j] = Math.max(dp[j], dp[j - 1] + (b[i + 1] === j ? 1 : 0));
}
}
// Check for the minimum removals
for (let j = N; j >= 0; j--) {
if (dp[j] >= K) {
return N - j;
}
}
return -1;
} // Driver Code let arr = [5, 1, 3, 2, 3]; let K = 2; let N = arr.length; console.log(minimumRemovals(arr, N, K)); |
Output:
2
Time Complexity: O(N^2)
Auxiliary Space: O(N)