Open In App

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

Last Updated : 10 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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)
 



Similar Reads

Count of array elements to be removed to make absolute difference between each pair same
Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be removed such that the absolute difference between each element pair is equal. Examples: Input: arr[] = {1, 2}Output: 0Explanation: There is only one pair of integers with absolute difference | arr[1] ? arr[2] | = | 1- 2 | = 1. So the
7 min read
Minimize count of array elements to be removed such that at least K elements are equal to their index values
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 = 2Output: 2 Explanati
13 min read
Minimize maximum difference between any pair of array elements by exactly one removal
Given an array arr[] consisting of N integers(N &gt; 2), the task is to minimize the maximum difference between any pair of elements (arr[i], arr[j]) by removing exactly one element. Examples: Input: arr[] = {1, 3, 4, 7}Output: 3Explanation:Removing the element 7 from array, modifies the array to {1, 3, 4}.Here (4, 1) has difference = 4 – 1 = 3 whi
9 min read
Maximize sum of product and difference between any pair of array elements possible
Given an array arr[] of size N, the task is to find the maximum value of arr[i] ∗ arr[j] + arr[i] − arr[j] for any pair (arr[i], arr[j]) from the given array, where i != j and 0 &lt; i, j &lt; N - 1. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 21Explanation:Among all the pairs of the array, the maximum value is obtained for the pair (arr[4], ar
10 min read
Maximize the minimum difference between any element pair by selecting K elements from given Array
Given an array of N integers the task is to select K elements out of these N elements in such a way that the minimum difference between each of the K numbers is the Largest. Return the largest minimum difference after choosing any K elements. Examples: Input: N = 4, K = 3, arr = [2, 6, 2, 5]Output: 1Explanation: 3 elements out of 4 elements are to
11 min read
Minimize count of 0s required to be removed to maximize length of longest substring of 1s
Given a binary string S of length N, the task is to find the minimum number of 0s required to be removed from the given string S to get the longest substring of 1s. Examples: Input: S = "010011"Output: 2Explanation:Removing str[2] and str[3] modifies the string S to "0111". Therefore, the minimum number of removals required is 2. Input: S = "011111
6 min read
Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half
Given an array arr[] consisting of N positive integers, the task is to minimize the maximum difference between any pair of array elements by multiplying any odd array element by 2 and dividing any even array element by 2. Examples: Input: arr[] = {4, 1, 5, 20, 3}Output: 3Explanation:Operation 1: Multiplying arr[1] by 2 modifies arr[] to {4, 2, 5, 2
7 min read
Minimum pairs required to be removed such that the array does not contain any pair with sum K
Given an array arr[] of size N and an integer K, the task is to find the minimum count of pairs required to be removed such that no pair exists in the array whose sum of elements is equal to K. Examples: Input: arr[] = { 3, 1, 3, 4, 3 }, K = 6 Output: 1 Explanation: Removing the pair (arr[0], arr[2]) modifies arr[] to arr[] = { 1, 4, 3 } Since no p
7 min read
Minimize product of first 2^K–1 Natural Numbers by swapping bits for any pair any number of times
Given a positive integer K, the task is to minimize the positive product of the first (2K - 1) Natural Numbers by swapping the bits at the corresponding position of any two numbers any number of times. Examples: Input: K = 3Output: 1512Explanation: The original product is 5040. The given array in binary notation is {001, 010, 011, 100, 101, 110, 11
5 min read
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays
Given an array arr[] consisting of N integers, the task is to print the indices of two array elements required to be removed such that the given array can be split into three subarrays of equal sum. If not possible to do so, then print "-1". Examples: Input: arr[] = {2, 5, 12, 7, 19, 4, 3}Output: 2 4Explanation:Removing arr[2] and arr[4] modifies a
21 min read