Minimize difference between maximum and minimum array elements by exactly K removals

Given an array arr[] consisting of N positive integers and an integer K, the task is to minimize the difference between the maximum and minimum element in the given array after removing exactly K elements.
Examples:
Input: arr[] = {5, 1, 6, 7, 12, 10}, K = 3
Output: 2
Explanation:
Remove elements 12, 10 and 1 from the given array.
The array modifies to {5, 6, 7}.
The difference between the minimum and maximum element is 7 – 5 = 2.Input: arr[] = {14, 5, 61, 10, 21, 12, 54}, K = 4
Output: 4
Explanation:
Remove elements 61, 54, 5 and 21 from the given array.
The array modifies to {14, 10, 12}.
The difference between the minimum and maximum element is 14 – 10 = 4.
Approach: The idea to solve the given problem is that the difference will be minimized by removing either the minimum element in an array or the maximum element in the array. Follow the steps below to solve the problem:
- Sort the array arr[] in ascending order.
- Initialize variables left = 0 and right = (N – 1).
- Iterate for K times and change the maximum or minimum to 0 according to the following condition:
- If arr[right – 1] – arr[left] < arr[right] – arr[left + 1], then change arr[right] to 0 and decrement right pointer by 1.
- Else, change arr[left] as 0 and increment the left pointer by 1.
- After the above steps, the difference between the elements at the left and right index is the required minimum difference.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>#include <iostream>using namespace std;Â
// Function to minimize the difference// of the maximum and minimum array// elements by removing K elementsvoid minimumRange(int arr[], int N, int K){    // Base Condition    if (K >= N)     {        cout << 0;        return;    }Â
    // Sort the array    sort(arr, arr + N);Â
    // Initialize left and right pointers    int left = 0, right = N - 1, i;Â
    // Iterate for K times    for (i = 0; i < K; i++)    {Â
        // Removing right element        // to reduce the difference        if (arr[right - 1] - arr[left]            < arr[right] - arr[left + 1])            right--;Â
        // Removing the left element        // to reduce the difference        else            left++;    }Â
    // Print the minimum difference    cout << arr[right] - arr[left];}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 5, 10, 12, 14, 21, 54, 61 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    int K = 4;Â
    // Function Call    minimumRange(arr, N, K);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â
// Function to minimize the difference// of the maximum and minimum array// elements by removing K elementsstatic void minimumRange(int arr[], int N,                          int K){         // Base Condition    if (K >= N)    {        System.out.print(0);        return;    }         // Sort the array    Arrays.sort(arr);         // Initialize left and right pointers    int left = 0, right = N - 1, i;Â
    // Iterate for K times    for(i = 0; i < K; i++)     {                 // Removing right element        // to reduce the difference        if (arr[right - 1] - arr[left] <             arr[right] - arr[left + 1])            right--;                     // Removing the left element        // to reduce the difference        else            left++;    }         // Print the minimum difference    System.out.print(arr[right] - arr[left]);}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int arr[] = { 5, 10, 12, 14, 21, 54, 61 };Â Â Â Â int N = arr.length;Â Â Â Â int K = 4;Â
    // Function Call    minimumRange(arr, N, K);}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program for the above approachÂ
# Function to minimize the difference# of the maximum and minimum array# elements by removing K elementsdef minimumRange(arr, N, K) :Â
    # Base Condition    if (K >= N) :        print(0, end = '');        return;Â
    # Sort the array    arr.sort();Â
    # Initialize left and right pointers    left = 0; right = N - 1;Â
    # Iterate for K times    for i in range(K) :Â
        # Removing right element        # to reduce the difference        if (arr[right - 1] - arr[left] < arr[right] - arr[left + 1]) :            right -= 1;Â
        # Removing the left element        # to reduce the difference        else :            left += 1;Â
    # Print the minimum difference    print(arr[right] - arr[left], end = '');Â
# Driver Codeif __name__ == "__main__" :Â
    arr = [ 5, 10, 12, 14, 21, 54, 61 ];    N = len(arr);Â
    K = 4;Â
    # Function Call    minimumRange(arr, N, K);Â
    # This code is contributed by AnkitRai01 |
C#
// C# program for the above approachusing System;class GFG{Â
// Function to minimize the difference// of the maximum and minimum array// elements by removing K elementsstatic void minimumRange(int []arr, int N,                          int K){         // Base Condition    if (K >= N)    {        Console.Write(0);        return;    }         // Sort the array    Array.Sort(arr);         // Initialize left and right pointers    int left = 0, right = N - 1, i;Â
    // Iterate for K times    for(i = 0; i < K; i++)     {                 // Removing right element        // to reduce the difference        if (arr[right - 1] - arr[left] <             arr[right] - arr[left + 1])            right--;                     // Removing the left element        // to reduce the difference        else            left++;    }         // Print the minimum difference    Console.Write(arr[right] - arr[left]);}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int []arr = { 5, 10, 12, 14, 21, 54, 61 };Â Â Â Â int N = arr.Length;Â Â Â Â int K = 4;Â
    // Function Call    minimumRange(arr, N, K);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Function to minimize the difference// of the maximum and minimum array// elements by removing K elementsfunction minimumRange(arr, N, K){    // Base Condition    if (K >= N)     {        document.write( 0);        return;    }Â
    // Sort the array    arr.sort((a,b)=> a-b);Â
    // Initialize left and right pointers    var left = 0, right = N - 1, i;Â
    // Iterate for K times    for (i = 0; i < K; i++)    {Â
        // Removing right element        // to reduce the difference        if (arr[right - 1] - arr[left]            < arr[right] - arr[left + 1])            right--;Â
        // Removing the left element        // to reduce the difference        else            left++;    }Â
    // Print the minimum difference    document.write( arr[right] - arr[left]);}Â
// Driver Codevar arr = [5, 10, 12, 14, 21, 54, 61];var N = arr.length;var K = 4;Â
// Function CallminimumRange(arr, N, K);Â
</script> |
4
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



