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 Â
- Then 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 <bits/stdc++.h> using namespace std; Â
// Function to find minimum difference // between largest and smallest element // after K replacements int 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 Code int 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 replacements Â
Â
def 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 Code if __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 approach using System; Â
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         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 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         Console.WriteLine(minDiff(A, K));     } } Â
// This code is contributed by shikhasingrajput |
Javascript
<script>     // Javascript program for the above approach          // Function to find minimum difference     // between largest and smallest element     // after K replacements     function minDiff(A, K)     { Â
        // Sort array in ascending order         A.sort( function (a, b){ return a - b}); Â
        // Length of array         let n = A.length; Â
        if (n <= K)             return 0; Â
        // Minimum difference         let mindiff = A[n - 1] - A[0]; Â
        if (K == 0)             return mindiff; Â
        // Check for all K + 1 possibilities         for (let i = 0, j = n - 1 - K; j < n;)         {             mindiff = Math.min(mindiff, A[j] - A[i]); Â
            i++;             j++;         } Â
        // Return answer         return mindiff;     }          // Given array     let A = [ -1, 3, -1, 8, 5, 4 ];     let K = 3;       // Prints the minimum possible difference     document.write(minDiff(A, K));          // This code is contributed by mukesh07. </script> |
2
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Heap-based Approach: This approach is similar to the above approach, but we will find the K minimum and K maximum array elements using Min Heap and Max Heap respectively.
Follow the steps below to solve the problem:Â
- Initialize two PriorityQueues, min-heap and max-heap.
- 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.
- 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.
- Iterate over the arrays and for every index, say i, update minDiff as minDiff = min(minDiff, maxList[i]-minList[ K – i ]) 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 <bits/stdc++.h> using namespace std; Â
// Function to find minimum difference // between the largest and smallest // element after K replacements int minDiff( int A[], int K, int N) { Â Â Â Â if (N <= K + 1) Â Â Â Â Â Â Â Â return 0; Â
    // Create a MaxHeap     priority_queue< int , vector< int >, greater< int > > maxHeap; Â
    // Create a MinHeap     priority_queue< int > 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< int > maxList;     while (maxHeap.size() > 0) {         maxList.push_back(maxHeap.top());         maxHeap.pop();     } Â
    // Store all min element from minHeap     vector< int > 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 Code int 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.lang.*; import java.util.*; Â
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<Integer> maxHeap             = new PriorityQueue<>(); Â
        // Create a MinHeap         PriorityQueue<Integer> 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<Integer> maxList = new ArrayList<>();         while (maxHeap.size() > 0 )             maxList.add(maxHeap.poll()); Â
        // Store all min element from minHeap         List<Integer> 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 approach import sys import heapq # Function to find minimum difference # between the largest and smallest # element after K replacements Â
Â
def minDiff(A, K):     if ( len (A) < = K + 1 ):         return 0     # Create a MaxHeap     maxHeap = []     heapq.heapify(maxHeap)     # Create a MinHeap     minHeap = []     heapq.heapify(minHeap)     # Update maxHeap and MinHeap with highest     # and smallest K elements respectively     for n in A:         # Insert current element         # into the MaxHeap         heapq.heappush(maxHeap, n)         # If maxHeap size exceeds K + 1         if ( len (maxHeap) > K + 1 ):             # Remove top element             heapq.heappop(maxHeap)         # Insert current element         # into the MaxHeap         heapq.heappush(minHeap, - n)         # If maxHeap size exceeds K + 1         if ( len (minHeap) > K + 1 ):             # Remove top element             heapq.heappop(minHeap)     # Store all max element from maxHeap     maxList = []     while ( len (maxHeap) > 0 ):         maxList.append(heapq.heappop(maxHeap))     # Store all min element from minHeap     minList = []     while ( len (minHeap) > 0 ):         minList.append( - 1 * heapq.heappop(minHeap))     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 Â
Â
# Drive Code if __name__ = = "__main__" :     # Given array     A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ]     K = 3     # Function call     print (minDiff(A, K))     # This code is contributed by divyesh072019. |
C#
// C# program for above approach using System; using System.Collections.Generic; Â
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         List< int > maxHeap = new List< int >(); Â
        // Create a MinHeap         List< int > minHeap = new List< int >(); Â
        // 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< int > maxList = new List< int >(); Â
        while (maxHeap.Count > 0) {             maxList.Add(maxHeap[0]);             maxHeap.RemoveAt(0);         } Â
        // Store all min element from minHeap         List< int > minList = new List< int >(); Â
        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 code     static 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 |
Javascript
<script> Â
// Javascript program for above approach Â
// Function to find minimum difference // between the largest and smallest // element after K replacements function minDiff(A, K, N) { Â Â Â Â if (N <= K + 1) Â Â Â Â Â Â Â Â return 0; Â
    // Create a MaxHeap     var maxHeap = []; Â
    // Create a MinHeap     var minHeap = []; Â
    // Update maxHeap and MinHeap with highest     // and smallest K elements respectively     for ( var i = 0; i < N; i++)     { Â
        // Insert current element         // into the MaxHeap         maxHeap.push(A[i]);         maxHeap.sort((a,b)=>b-a); Â
        // If maxHeap size exceeds K + 1         if (maxHeap.length > K + 1) Â
            // Remove top element             maxHeap.pop(); Â
        // Insert current element         // into the MaxHeap         minHeap.push(A[i]);         minHeap.sort((a,b)=>a-b); Â
        // If maxHeap size exceeds K + 1         if (minHeap.length > K + 1) Â
            // Remove top element             minHeap.pop();     } Â
    // Store all max element from maxHeap     var maxList = [];     while (maxHeap.length > 0)     {         maxList.push(maxHeap[maxHeap.length-1]);         maxHeap.pop();     } Â
    // Store all min element from minHeap     var minList = [];     while (minHeap.length > 0)     {         minList.push(minHeap[minHeap.length-1]);         minHeap.pop();     } Â
    var mindiff = 1000000000; Â
    // Generating all K + 1 possibilities     for ( var i = 0; i <= K; i++)     {         mindiff = Math.min(mindiff, maxList[i] - minList[K - i]);     }        // Return answer     return mindiff; } Â
// Driver Code // Given array var A = [-1, 3, -1, 8, 5, 4]; var N = A.length; var K = 3; Â
// Function call document.write(minDiff(A, K, N)); Â
// This code is contributed by noob2000. </script> |
2
Time Complexity: O(N*log N) where N is the size of the given array.
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!