Related Articles

# Minimize difference between the largest and smallest array elements by K replacements

• Difficulty Level : Hard
• Last Updated : 22 Apr, 2021

Given an array A[] consisting of N integers, the task is to find the minimum difference between the largest and the smallest element in the given array after replacing K elements.

Examples:

Input: A[] = {-1, 3, -1, 8, 5, 4}, K = 3
Output: 2
Explanation:Replace A[0] and A[2] by 3 and 4 respectively. Replace A[3] by 5. Modified array A[] is {3, 3, 4, 5, 5, 4}. Therefore, required output = (5-3) = 2.

Input: A[] = {10, 10, 3, 4, 10}, K = 2
Output: 0

Sorting Approach: The idea is to sort the given array. Check for all K + 1 possibilities of removing X ( 0 ≤ X ≤ K ) elements from the start of the array and removing K – X elements from the end of the array and calculate the minimum difference possible. Finally, print the minimum difference obtained.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach#include using namespace std; // Function to find minimum difference// between largest and smallest element// after K replacementsint minDiff(int A[], int K, int n){         // Sort array in ascending order    sort(A, A + n);         if (n <= K)        return 0;     // Minimum difference    int mindiff = A[n - 1] - A[0];         if (K == 0)        return mindiff;     // Check for all K + 1 possibilities    for(int i = 0, j = n - 1 - K; j < n;)    {        mindiff = min(            mindiff, A[j] - A[i]);         i++;        j++;    }     // Return answer    return mindiff;} // Driver Codeint main(){         // Given array    int A[] = { -1, 3, -1, 8, 5, 4 };    int K = 3;         // Length of array    int n = sizeof(A) / sizeof(A[0]);         // Prints the minimum possible difference    cout << minDiff(A, K, n);         return 0;} // This code is contributed by 29AjayKumar

## Java

 // Java program for the above approach import java.util.*; class GFG {     // Function to find minimum difference    // between largest and smallest element    // after K replacements    static int minDiff(int[] A, int K)    {        // Sort array in ascending order        Arrays.sort(A);         // Length of array        int n = A.length;         if (n <= K)            return 0;         // Minimum difference        int mindiff = A[n - 1] - A[0];        if (K == 0)            return mindiff;         // Check for all K + 1 possibilities        for (int i = 0, j = n - 1 - K; j < n;) {            mindiff = Math.min(                mindiff, A[j] - A[i]);             i++;            j++;        }         // Return answer        return mindiff;    }     // Driver Code    public static void main(String[] args)    {        // Given array        int A[] = { -1, 3, -1, 8, 5, 4 };        int K = 3;         // Prints the minimum possible difference        System.out.println(minDiff(A, K));    }}

## Python3

 # Python3 program for the above approach # Function to find minimum difference# between largest and smallest element# after K replacementsdef minDiff(A, K):       # Sort array in ascending order    A.sort();     # Length of array    n = len(A);    if (n <= K):        return 0;     # Minimum difference    mindiff = A[n - 1] - A[0];    if (K == 0):        return mindiff;     # Check for all K + 1 possibilities    i = 0;    for j in range(n - 1 - K, n):        mindiff = min(mindiff, A[j] - A[i]);         i += 1;        j += 1;     # Return answer    return mindiff; # Driver Codeif __name__ == '__main__':         # Given array    A = [-1, 3, -1, 8, 5, 4];    K = 3;     # Prints the minimum possible difference    print(minDiff(A, K));     # This code is contributed by 29AjayKumar

## C#

 // C# program for the above approachusing System; class GFG{ // Function to find minimum difference// between largest and smallest element// after K replacementsstatic int minDiff(int[] A, int K){         // Sort array in ascending order    Array.Sort(A);     // Length of array    int n = A.Length;     if (n <= K)        return 0;     // Minimum difference    int mindiff = A[n - 1] - A[0];         if (K == 0)        return mindiff;     // Check for all K + 1 possibilities    for(int i = 0, j = n - 1 - K; j < n;)    {        mindiff = Math.Min(            mindiff, A[j] - A[i]);         i++;        j++;    }     // Return answer    return mindiff;} // Driver Codepublic static void Main(String[] args){         // Given array    int []A = { -1, 3, -1, 8, 5, 4 };    int K = 3;     // Prints the minimum possible difference    Console.WriteLine(minDiff(A, K));}} // This code is contributed by shikhasingrajput

## Javascript


Output:
2

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

Heap-based Approach: This approach is similar to the above approach. Find the K minimum and K maximum array elements using Min Heap and Max Heap respectively.

Follow the steps below to solve the problem:

1. Initialize two PriorityQueues, min-heap and max-heap.
2. Traverse the given array and add all elements one by one into the Heaps. If the size of the Heap exceeds K, in any of the heaps, remove the element present at the top of that Queue.
3. Store the K maximum and the minimum elements in two separate arrays, maxList and minList, and initialize a variable, say minDiff to store the minimum difference.
4. Iterate over the arrays and for every index, say i, update minDiff as minDiff = min(minDiff, maxList[i]-minList[K – 1]) and print final value of minDiff as the required answer.

Below is the implementation of the above approach:

## C++

 // C++ program for above approach#include using namespace std; // Function to find minimum difference// between the largest and smallest// element after K replacementsint minDiff(int A[], int K, int N){    if (N <= K + 1)        return 0;     // Create a MaxHeap    priority_queue, greater>        maxHeap;     // Create a MinHeap    priority_queue minHeap;     // Update maxHeap and MinHeap with highest    // and smallest K elements respectively    for (int i = 0; i < N; i++)    {         // Insert current element        // into the MaxHeap        maxHeap.push(A[i]);         // If maxHeap size exceeds K + 1        if (maxHeap.size() > K + 1)             // Remove top element            maxHeap.pop();         // Insert current element        // into the MaxHeap        minHeap.push(A[i]);         // If maxHeap size exceeds K + 1        if (minHeap.size() > K + 1)             // Remove top element            minHeap.pop();    }     // Store all max element from maxHeap    vector maxList;    while (maxHeap.size() > 0)    {        maxList.push_back(maxHeap.top());        maxHeap.pop();    }     // Store all min element from minHeap    vector minList;    while (minHeap.size() > 0)    {        minList.push_back(minHeap.top());        minHeap.pop();    }     int mindiff = INT_MAX;     // Generating all K + 1 possibilities    for (int i = 0; i <= K; i++)    {        mindiff = min(mindiff, maxList[i] - minList[K - i]);    }       // Return answer    return mindiff;} // Driver Codeint main(){     // Given array    int A[] = { -1, 3, -1, 8, 5, 4 };    int N = sizeof(A) / sizeof(A[0]);    int K = 3;     // Function call    cout << minDiff(A, K, N);    return 0;} // This code is contributed by Dharanendra L V

## Java

 // Java program for above approach import java.util.*;import java.lang.*; class GFG {     // Function to find minimum difference    // between the largest and smallest    // element after K replacements    static int minDiff(int[] A, int K)    {        if (A.length <= K + 1)            return 0;         // Create a MaxHeap        PriorityQueue maxHeap            = new PriorityQueue<>();         // Create a MinHeap        PriorityQueue minHeap            = new PriorityQueue<>(                Collections.reverseOrder());         // Update maxHeap and MinHeap with highest        // and smallest K elements respectively        for (int n : A) {             // Insert current element            // into the MaxHeap            maxHeap.add(n);             // If maxHeap size exceeds K + 1            if (maxHeap.size() > K + 1)                 // Remove top element                maxHeap.poll();             // Insert current element            // into the MaxHeap            minHeap.add(n);             // If maxHeap size exceeds K + 1            if (minHeap.size() > K + 1)                 // Remove top element                minHeap.poll();        }         // Store all max element from maxHeap        List maxList = new ArrayList<>();        while (maxHeap.size() > 0)            maxList.add(maxHeap.poll());         // Store all min element from minHeap        List minList = new ArrayList<>();        while (minHeap.size() > 0)            minList.add(minHeap.poll());         int mindiff = Integer.MAX_VALUE;         // Generating all K + 1 possibilities        for (int i = 0; i <= K; i++) {            mindiff = Math.min(mindiff,                               maxList.get(i)                                   - minList.get(K - i));        }        // Return answer        return mindiff;    }     // Driver Code    public static void main(String[] args)    {         // Given array        int A[] = { -1, 3, -1, 8, 5, 4 };        int K = 3;         // Function call        System.out.println(minDiff(A, K));    }}

## Python3

 # Python3 program for above approachimport sys # Function to find minimum difference# between the largest and smallest# element after K replacementsdef minDiff(A, K) :    if (len(A) <= K + 1) :        return 0              # Create a MaxHeap    maxHeap = []      # Create a MinHeap    minHeap = []      # Update maxHeap and MinHeap with highest    # and smallest K elements respectively    for n in A :                  # Insert current element        # into the MaxHeap        maxHeap.append(n)        maxHeap.sort()                  # If maxHeap size exceeds K + 1        if (len(maxHeap) > K + 1) :              # Remove top element            del maxHeap[0]          # Insert current element        # into the MaxHeap        minHeap.append(n)        minHeap.sort()        minHeap.reverse()                  # If maxHeap size exceeds K + 1        if (len(minHeap) > K + 1) :              # Remove top element            del minHeap[0]          # Store all max element from maxHeap    maxList = []          while (len(maxHeap) > 0) :             maxList.append(maxHeap[0])        del maxHeap[0]          # Store all min element from minHeap    minList = []          while (len(minHeap) > 0) :         minList.append(minHeap[0])        del minHeap[0]    mindiff = sys.maxsize      # Generating all K + 1 possibilities    for i in range(K) :             mindiff = min(mindiff, maxList[i] - minList[K - i])          # Return answer    return mindiff     # Given arrayA = [ -1, 3, -1, 8, 5, 4 ]K = 3  # Function callprint(minDiff(A, K)) # This code is contributed by divyesh072019.

## C#

 // C# program for above approachusing System;using System.Collections.Generic; class GFG{     // Function to find minimum difference// between the largest and smallest// element after K replacementsstatic int minDiff(int[] A, int K){    if (A.Length <= K + 1)        return 0;             // Create a MaxHeap    List maxHeap = new List();     // Create a MinHeap    List minHeap = new List();     // Update maxHeap and MinHeap with highest    // and smallest K elements respectively    foreach(int n in A)    {                 // Insert current element        // into the MaxHeap        maxHeap.Add(n);        maxHeap.Sort();                 // If maxHeap size exceeds K + 1        if (maxHeap.Count > K + 1)             // Remove top element            maxHeap.RemoveAt(0);         // Insert current element        // into the MaxHeap        minHeap.Add(n);        minHeap.Sort();        minHeap.Reverse();                 // If maxHeap size exceeds K + 1        if (minHeap.Count > K + 1)             // Remove top element            minHeap.RemoveAt(0);    }         // Store all max element from maxHeap    List maxList = new List();         while (maxHeap.Count > 0)    {        maxList.Add(maxHeap[0]);        maxHeap.RemoveAt(0);    }         // Store all min element from minHeap    List minList = new List();         while (minHeap.Count > 0)    {        minList.Add(minHeap[0]);        minHeap.RemoveAt(0);    }         int mindiff = Int32.MaxValue;     // Generating all K + 1 possibilities    for(int i = 0; i < K; i++)    {        mindiff = Math.Min(mindiff,                           maxList[i] -                           minList[K - i]);    }         // Return answer    return mindiff;} // Driver codestatic void Main(){         // Given array    int[] A = { -1, 3, -1, 8, 5, 4 };    int K = 3;         // Function call    Console.WriteLine(minDiff(A, K));}} // This code is contributed by divyeshrabadiya07
Output:
2

Time Complexity: O(NlogN) where N is the size of the given array.
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up