Minimize maximum difference between any pair of array elements by exactly one removal

Given an array arr[] consisting of N integers(N > 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: 3
Explanation:
Removing the element 7 from array, modifies the array  to {1, 3, 4}.
Here (4, 1) has difference = 4 – 1 = 3 which is minimum possible maximum difference.ÂInput: arr[] = {1, 2, 3, 4}
Output: 2
Naive Approach: The simplest approach to solve the given problem is to remove every element one by one and check which element gives the minimized maximum difference between every pair of elements.
Time Complexity: O(N3)
Auxiliary Space: O(N)Â
Efficient Approach: The above approach can also be optimized by observing the fact that the maximum difference is equal to the difference between the maximum and the minimum element of the given array. So, removing the maximum element or removing the minimum element always gives the optimal answer.
Therefore, the idea is to sort the given array in ascending order and print the minimum of the value (arr[N – 2] – arr[0]) and (arr[N – 1] – arr[1]) as the resultant minimized maximum difference.
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 the minimum maximum// difference after removing one elementint findMinDifference(int arr[], int n){    // Stores the resultant minimized    // maximum difference    int ans = 0;Â
    // Sort the given array    sort(arr, arr + n);Â
    // Find the minimum maximum    // difference    ans = min(arr[n - 2] - arr[0],              arr[n - 1] - arr[1]);Â
    // Return the result    return ans;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 1, 3, 4, 7 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << findMinDifference(arr, N);Â
    return 0;} |
Java
// Java program for the above approachÂ
import java.io.*;import java.util.*;Â
class GFG {Â
  // Function to find the minimum maximum  // difference after removing one element  static int findMinDifference(int []arr, int n)  {Â
    // Stores the resultant minimized    // maximum difference    int ans = 0;Â
    // Sort the given array    Arrays.sort(arr);Â
    // Find the minimum maximum    // difference    ans = Math.min(arr[n - 2] - arr[0],                   arr[n - 1] - arr[1]);Â
    // Return the result    return ans;  }Â
  // Driver CodeÂ
  public static void main (String[] args) {Â
    int []arr = { 1, 3, 4, 7 };    int N = arr.length;Â
Â
    System.out.println(findMinDifference(arr, N));  }Â
}Â
// This code is contributed by unknown2108 |
Python3
# Python3 program for the above approachÂ
# Function to find the minimum maximum# difference after removing one elementdef findMinDifference(arr, n):         # Stores the resultant minimized    # maximum difference    ans = 0Â
    # Sort the given array    arr = sorted(arr)Â
    # Find the minimum maximum    # difference    ans = min(arr[n - 2] - arr[0],               arr[n - 1] - arr[1])Â
    # Return the result    return ansÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â arr = [ 1, 3, 4, 7 ]Â Â Â Â N = len(arr)Â Â Â Â Â Â Â Â Â print (findMinDifference(arr, N))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Function to find the minimum maximum// difference after removing one elementstatic int findMinDifference(int []arr, int n){         // Stores the resultant minimized    // maximum difference    int ans = 0;Â
    // Sort the given array    Array.Sort(arr);Â
    // Find the minimum maximum    // difference    ans = Math.Min(arr[n - 2] - arr[0],                   arr[n - 1] - arr[1]);Â
    // Return the result    return ans;}Â
// Driver Codepublic static void Main(){Â Â Â Â int []arr = { 1, 3, 4, 7 };Â Â Â Â int N = arr.Length;Â Â Â Â Â Â Â Â Â Console.Write(findMinDifference(arr, N));}}Â
// This code is contributed by ipg2016107 |
Javascript
<script>// Javascript program for the above approachÂ
// Function to find the minimum maximum// difference after removing one elementfunction findMinDifference(arr, n){Â
    // Stores the resultant minimized    // maximum difference    let ans = 0;      // Sort the given array    arr.sort(function(a,b){return a-b;});      // Find the minimum maximum    // difference    ans = Math.min(arr[n - 2] - arr[0],                   arr[n - 1] - arr[1]);      // Return the result    return ans;}Â
// Driver Codelet arr=[1, 3, 4, 7];let N = arr.length;document.write(findMinDifference(arr, N));Â
// This code is contributed by patel2127</script> |
3
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Efficient Approach:-Â
- As in the above approach we are either removing the maximum element or the minimum element
- So we can do this work without sortingÂ
- We have to just find out the 2 maximum and 2 minimum elements from the array
- Answer will be minimum of (2nd largest-first minimum) or (first lasgest-second minimum).
Implementation:-
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the minimum maximum// difference after removing one elementint findMinDifference(int arr[], int n){         //taking variables to store 2 max and 2 min elements      int firstmin=INT_MAX,secondmin=INT_MAX,firstmax=INT_MIN,secondmax=INT_MIN;         //iterating over array      for(int i=0;i<n;i++)    {                 //if found min element than firstmin          if(arr[i]<firstmin)        {              //updating secondmin              secondmin=firstmin;              //updating firstmin              firstmin=arr[i];        }                 //if found element small than secondmin          else if(arr[i]<secondmin)        {              secondmin=arr[i];        }                 //if found element larger than firstmax          if(arr[i]>firstmax)        {              //updating second max              secondmax=firstmax;              //updating first max              firstmax=arr[i];        }                 //if found element greater than second max          else if(arr[i]>secondmax)          {              secondmax=arr[i];        }          }         //returning answer      return min(secondmax-firstmin,firstmax-secondmin);       }Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 1, 3, 4, 7 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << findMinDifference(arr, N);Â
    return 0;}//This code is contributed by shubhamrajput6156 |
Java
// Java program for the above approachÂ
import java.lang.*;import java.util.*;Â
class Main {    // Function to find the minimum maximum    // difference after removing one element    static int findMinDifference(int arr[], int n)    {            // taking variables to store 2 max and 2 min            // elements            int firstmin            = Integer.MAX_VALUE,            secondmin = Integer.MAX_VALUE,            firstmax = Integer.MIN_VALUE,            secondmax = Integer.MIN_VALUE;Â
        // iterating over array        for (int i = 0; i < n; i++) {Â
            // if found min element than firstmin            if (arr[i] < firstmin) {                // updating secondmin                secondmin = firstmin;                // updating firstmin                firstmin = arr[i];            }Â
            // if found element small than secondmin            else if (arr[i] < secondmin) {                secondmin = arr[i];            }Â
            // if found element larger than firstmax            if (arr[i] > firstmax) {                // updating second max                secondmax = firstmax;                // updating first max                firstmax = arr[i];            }Â
            // if found element greater than second max            else if (arr[i] > secondmax) {                secondmax = arr[i];            }        }Â
        // returning answer        return Math.min(secondmax - firstmin,                        firstmax - secondmin);    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[] = { 1, 3, 4, 7 };        int N = arr.length;        System.out.println(findMinDifference(arr, N));    }} |
Python3
# Python program for the above approachimport sysÂ
# Function to find the minimum maximum# difference after removing one element def findMinDifference(arr, n):       # taking variables to store 2 max and 2 min elements    firstmin = sys.maxsize    secondmin = sys.maxsize    firstmax = -sys.maxsize - 1    secondmax = -sys.maxsize - 1        for i in range(n):               # if found min element than firstmin        if arr[i] < firstmin:            # updating secondmin            secondmin = firstmin            #updating firstmin            firstmin = arr[i]                     # if found element small than secondmin        elif arr[i] < secondmin:            secondmin = arr[i]                # if found element larger than firstmax        if arr[i] > firstmax:            # update second max            secondmax = firstmax            # update first max            firstmax = arr[i]                # if found element greater than second max        elif arr[i] > secondmax:            secondmax = arr[i]                 # returning answer    return min(secondmax - firstmin, firstmax - secondmin)  # driver codearr = [1, 3, 4, 7]N = len(arr)print(findMinDifference(arr, N))Â
# This code is contributed by redmoonz. |
Javascript
// Java program for the above approachÂ
    // Function to find the minimum maximum    // difference after removing one element    const findMinDifference = (arr, n) => {         // taking variables to store 2 max and 2 min    // elements    let firstmin = Number.MAX_SAFE_INTEGER;    let secondmin = Number.MAX_SAFE_INTEGER;    let firstmax = Number.MIN_SAFE_INTEGER;    let secondmax = Number.MIN_SAFE_INTEGER;Â
// iterating over array    for (let i = 0; i < n; i++) {         // if found min element than firstmin        if (arr[i] < firstmin) {            secondmin = firstmin;            firstmin = arr[i];        } else if (arr[i] < secondmin) {            secondmin = arr[i];        }Â
        if (arr[i] > firstmax) {            secondmax = firstmax;            firstmax = arr[i];                         // if found element greater than second max        } else if (arr[i] > secondmax) {            secondmax = arr[i];        }    }Â
    // returning answer    return Math.min(secondmax - firstmin, firstmax - secondmin);}Â
const arr = [1, 3, 4, 7];const n = arr.length;console.log(findMinDifference(arr, n)); |
C#
// C# program for the above approachÂ
using System;Â
public class GFG{Â
    // Function to find the minimum maximum    // difference after removing one element    public static int findMinDifference(int[] arr, int n)    {Â
          //taking variables to store 2 max and 2 min elements          int firstmin = int.MaxValue;          int secondmin = int.MaxValue;          int firstmax = int.MinValue;          int secondmax = int.MinValue;Â
          //iterating over array          for (int i = 0;i < n;i++)          {Â
              //if found min element than firstmin              if (arr[i] < firstmin)              {                  //updating secondmin                  secondmin = firstmin;                  //updating firstmin                  firstmin = arr[i];              }Â
              //if found element small than secondmin              else if (arr[i] < secondmin)              {                  secondmin = arr[i];              }Â
              //if found element larger than firstmax              if (arr[i] > firstmax)              {                  //updating second max                  secondmax = firstmax;                  //updating first max                  firstmax = arr[i];              }Â
              //if found element greater than second max              else if (arr[i] > secondmax)              {                  secondmax = arr[i];              }          }Â
          //returning answer          return Math.Min(secondmax - firstmin,firstmax - secondmin);Â
    }Â
    // Driver Code    internal static void Main()    {        int[] arr = {1, 3, 4, 7};Â
        int N = arr.Length;        Console.Write(findMinDifference(arr, N));Â
    }    //This code is contributed by bhardwajji} |
3
Time Complexity:- O(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!



