Skip to content
Related Articles

Related Articles

Improve Article

Minimize count of array elements to be removed to maximize difference between any pair up to K

  • Last Updated : 10 May, 2021
Geek Week

Given an array arr[] and an integer K, the task is to count the number of elements to be removed from the array such that the difference of the maximum and the minimum number left does not exceed K.

Examples:

Input: K = 1, arr[] = {1, 2, 3, 4, 5} 
Output:
Explanation: 
Removal of {5, 4, 3} modifies array to {1, 2} where the maximum difference is 1(= K).
Input: K = 3, arr[] = {1, 2, 3, 4, 5} 
Output:
Explanation: 
Removal of {5} modifies array to {1, 2, 3, 4} where the maximum difference is 3(= K).

Approach: 
The task is to find the difference between the maximum and minimum array element which should not exceed K.

  • Sort the array in ascending order and initialize a variable to a minimum value.
  • Iterate over the array to generate all possible pairs and check if the difference between any pair is less than or equal to K.
  • Update the minimum number of removals for each pair.
  • Finally, print the minimum removals obtained.

Below is the implementation of the above approach:



C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of
// elements to be removed from the
// array based on the given condition
int min_remove(int arr[], int n, int k)
{
    // Sort the array
    sort(arr, arr + n);
 
    /// Initialize the variable
    int ans = INT_MAX;
 
    // Iterate for all possible pairs
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
 
            // Check the difference
            // between the numbers
            if (arr[j] - arr[i] <= k) {
 
                // Update the minimum removals
                ans = min(ans, n - j + i - 1);
            }
        }
    }
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    int k = 3;
    int arr[] = { 1, 2, 3, 4, 5 };
 
    int n = sizeof arr / sizeof arr[0];
 
    cout << min_remove(arr, n, k);
    return 0;
}

Java




// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to count the number of
// elements to be removed from the
// array based on the given condition
static int min_remove(int arr[], int n, int k)
{
    // Sort the array
    Arrays.sort(arr);
 
    /// Initialize the variable
    int ans = Integer.MAX_VALUE;
 
    // Iterate for all possible pairs
    for (int i = 0; i < n; i++)
    {
        for (int j = i; j < n; j++)
        {
 
            // Check the difference
            // between the numbers
            if (arr[j] - arr[i] <= k)
            {
 
                // Update the minimum removals
                ans = Math.min(ans, n - j + i - 1);
            }
        }
    }
    // Return the answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int k = 3;
    int arr[] = { 1, 2, 3, 4, 5 };
 
    int n = arr.length;
 
    System.out.print(min_remove(arr, n, k));
}
}
 
// This code is contributed by sapnasingh4991

Python3




# Python3 program to implement
# the above approach
import sys
 
# Function to count the number of
# elements to be removed from the
# array based on the given condition
def min_remove(arr, n, k):
 
    # Sort the array
    arr.sort()
 
    # Initialize the variable
    ans = sys.maxsize
 
    # Iterate for all possible pairs
    for i in range(n):
        for j in range(i, n):
 
            # Check the difference
            # between the numbers
            if (arr[j] - arr[i] <= k):
 
                # Update the minimum removals
                ans = min(ans, n - j + i - 1)
     
    # Return the answer
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    k = 3
    arr = [ 1, 2, 3, 4, 5 ]
 
    n = len(arr)
 
    print (min_remove(arr, n, k))
 
# This code is contributed by chitranayal

C#




// C# Program to implement
// the above approach
using System;
class GFG{
 
// Function to count the number of
// elements to be removed from the
// array based on the given condition
static int min_remove(int []arr, int n, int k)
{
    // Sort the array
    Array.Sort(arr);
 
    /// Initialize the variable
    int ans = int.MaxValue;
 
    // Iterate for all possible pairs
    for (int i = 0; i < n; i++)
    {
        for (int j = i; j < n; j++)
        {
 
            // Check the difference
            // between the numbers
            if (arr[j] - arr[i] <= k)
            {
 
                // Update the minimum removals
                ans = Math.Min(ans, n - j + i - 1);
            }
        }
    }
    // Return the answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    int k = 3;
    int []arr = { 1, 2, 3, 4, 5 };
 
    int n = arr.Length;
 
    Console.Write(min_remove(arr, n, k));
}
}
 
// This code is contributed by sapnasingh4991

Javascript




<script>
// JavaScript program for the above approach
 
// Function to count the number of
// elements to be removed from the
// array based on the given condition
function min_remove(arr, n, k)
{
    // Sort the array
    arr.sort();
   
    /// Initialize the variable
    let ans = Number.MAX_VALUE;
   
    // Iterate for all possible pairs
    for (let i = 0; i < n; i++)
    {
        for (let j = i; j < n; j++)
        {
   
            // Check the difference
            // between the numbers
            if (arr[j] - arr[i] <= k)
            {
   
                // Update the minimum removals
                ans = Math.min(ans, n - j + i - 1);
            }
        }
    }
    // Return the answer
    return ans;
}
       
// Driver Code
     
    let k = 3;
    let arr = [ 1, 2, 3, 4, 5 ];
   
    let n = arr.length;
   
    document.write(min_remove(arr, n, k));
                 
</script>
Output: 
1

 

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

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :