Minimize the maximum minimum difference after one removal from array

Given an array arr[] of size n ? 3, the task is to find the minimum possible difference between the maximum and the minimum element from the array after removing one element.
Examples:Â
Input: arr[] = {1, 2, 3}Â
Output: 1Â
Removing 1 will give 3 – 2 = 1Â
Removing 2, 3 – 1 = 2Â
And removing 3 will result in 2 – 1 = 1Input: arr[] = {1, 2, 4, 3, 4}Â
Output: 2Â
Naive Approach: It is clear that to have an effect on the difference only the minimum or the maximum element has to be removed.Â
- Sort the array.
- Remove the minimum, store diff1 = arr[n – 1] – arr[1].
- Remove the maximum, and diff2 = arr[n – 2] – arr[0].
- Print min(diff1, diff2) in the end.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the minimum required differenceint findMinDifference(int arr[], int n){    // Sort the given array    sort(arr, arr + n);Â
    // When minimum element is removed    int diff1 = arr[n - 1] - arr[1];Â
    // When maximum element is removed    int diff2 = arr[n - 2] - arr[0];Â
    // Return the minimum of diff1 and diff2    return min(diff1, diff2);}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 1, 2, 4, 3, 4 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    cout << findMinDifference(arr, n);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class solution{Â
// Function to return the minimum required differencestatic int findMinDifference(int arr[], int n){    // Sort the given array    Arrays.sort(arr);Â
    // When minimum element is removed    int diff1 = arr[n - 1] - arr[1];Â
    // When maximum element is removed    int diff2 = arr[n - 2] - arr[0];Â
    // Return the minimum of diff1 and diff2    return Math.min(diff1, diff2);}Â
// Driver Codepublic static void main(String args[]){    int arr[] = { 1, 2, 4, 3, 4 };    int n = arr.length;Â
    System.out.print(findMinDifference(arr, n));Â
}}// This code is contributed by// Sanjit_Prasad |
Python3
# Python3 implementation of the approach Â
# Function to return the minimum# required difference def findMinDifference(arr, n) :Â
    # Sort the given array     arr.sort() Â
    # When minimum element is removed     diff1 = arr[n - 1] - arr[1]Â
    # When maximum element is removed     diff2 = arr[n - 2] - arr[0] Â
    # Return the minimum of diff1 and diff2     return min(diff1, diff2) Â
# Driver Code if __name__ == "__main__" :Â
    arr = [ 1, 2, 4, 3, 4 ]     n = len(arr) Â
    print(findMinDifference(arr, n)) Â
# This code is contributed by Ryuga |
C#
// C# implementation of the approachusing System;Â
public class GFG{     // Function to return the minimum required differencestatic int findMinDifference(int []arr, int n){    // Sort the given array    Array.Sort(arr);Â
    // When minimum element is removed    int diff1 = arr[n - 1] - arr[1];Â
    // When maximum element is removed    int diff2 = arr[n - 2] - arr[0];Â
    // Return the minimum of diff1 and diff2    return Math.Min(diff1, diff2);}Â
// Driver Code    static public void Main (){         int []arr = { 1, 2, 4, 3, 4 };    int n = arr.Length;Â
    Console.Write(findMinDifference(arr, n));Â
}}// This code is contributed by Sachin.. |
PHP
<?php// PHP implementation of the approachÂ
// Function to return the minimum // required differencefunction findMinDifference($arr, $n){    // Sort the given array    sort($arr, 0);Â
    // When minimum element is removed    $diff1 = $arr[$n - 1] - $arr[1];Â
    // When maximum element is removed    $diff2 = $arr[$n - 2] - $arr[0];Â
    // Return the minimum of diff1 and diff2    return min($diff1, $diff2);}Â
// Driver Code$arr = array(1, 2, 4, 3, 4);$n = sizeof($arr);Â
echo findMinDifference($arr, $n);Â
// This code is contributed// by Akanksha Rai |
Javascript
<script>    // Javascript implementation of the approach          // Function to return the minimum required difference     function findMinDifference(arr, n)     {         // Sort the given array         arr.sort();                // When minimum element is removed         let diff1 = arr[n - 1] - arr[1];                // When maximum element is removed         let diff2 = arr[n - 2] - arr[0];                // Return the minimum of diff1 and diff2         return Math.min(diff1, diff2);     }          let arr = [ 1, 2, 4, 3, 4 ];     let n = arr.length;        document.write(findMinDifference(arr, n));      </script> |
2
Complexity Analysis:
- Time Complexity: O(nlogn)
- Auxiliary Space : O(1)
Efficient Approach: In order to find the min, secondMin, max and secondMax elements from the array. We don’t need to sort the array, it can be done in a single array traversal.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std;Â
// Function to return the minimum required differenceint findMinDifference(int arr[], int n){Â Â Â Â int min__, secondMin, max__, secondMax;Â
    min__ = secondMax = (arr[0] < arr[1]) ? arr[0] : arr[1];    max__ = secondMin = (arr[0] < arr[1]) ? arr[1] : arr[0];Â
    for (int i = 2; i < n; i++)    {        // If current element is greater than max        if (arr[i] > max__)        {            // max will become secondMax            secondMax = max__;Â
            // Update the max            max__ = arr[i];        }Â
        // If current element is greater than secondMax        // but smaller than max        else if (arr[i] > secondMax)        {Â
            // Update the secondMax            secondMax = arr[i];        }Â
        // If current element is smaller than min        else if (arr[i] < min__)         {Â
            // min will become secondMin            secondMin = min__;Â
            // Update the min            min__ = arr[i];        }Â
        // If current element is smaller than secondMin        // but greater than min        else if (arr[i] < secondMin) {                             // Update the secondMin            secondMin = arr[i];        }    }Â
    // Minimum of the two possible differences    int diff = min(max__ - secondMin, secondMax - min__);    return diff;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 2, 4, 3, 4 };Â Â Â Â int n = sizeof(arr)/sizeof(arr[0]);Â Â Â Â cout << (findMinDifference(arr, n));}Â Â Â Â Â // This code is contributed by// Shashank_Sharma |
Java
// Java implementation of the approachpublic class GFG {Â
    // Function to return the minimum required difference    static int findMinDifference(int arr[], int n)    {        int min, secondMin, max, secondMax;Â
        min = secondMax = (arr[0] < arr[1]) ? arr[0] : arr[1];        max = secondMin = (arr[0] < arr[1]) ? arr[1] : arr[0];Â
        for (int i = 2; i < n; i++) {Â
            // If current element is greater than max            if (arr[i] > max) {Â
                // max will become secondMax                secondMax = max;Â
                // Update the max                max = arr[i];            }Â
            // If current element is greater than secondMax            // but smaller than max            else if (arr[i] > secondMax) {Â
                // Update the secondMax                secondMax = arr[i];            }Â
            // If current element is smaller than min            else if (arr[i] < min) {Â
                // min will become secondMin                secondMin = min;Â
                // Update the min                min = arr[i];            }Â
            // If current element is smaller than secondMin            // but greater than min            else if (arr[i] < secondMin) {Â
                // Update the secondMin                secondMin = arr[i];            }        }Â
        // Minimum of the two possible differences        int diff = Math.min(max - secondMin, secondMax - min);Â
        return diff;    }Â
    // Driver code    public static void main(String[] args)    {        int arr[] = { 1, 2, 4, 3, 4 };        int n = arr.length;Â
        System.out.println(findMinDifference(arr, n));    }} |
Python3
# Python 3 implementation of the approachÂ
# Function to return the minimum# required differencedef findMinDifference(arr, n):Â Â Â Â Â Â Â Â Â if(arr[0] < arr[1]):Â Â Â Â Â Â Â Â min__ = secondMax = arr[0] Â Â Â Â else:Â Â Â Â Â Â Â Â min__ = secondMax = arr[1]Â Â Â Â Â Â Â Â Â Â Â Â Â if(arr[0] < arr[1]):Â Â Â Â Â Â Â Â max__ = secondMin = arr[1] Â Â Â Â else:Â Â Â Â Â Â Â Â max__ = secondMin = arr[0]Â
    for i in range(2, n):                 # If current element is greater        # than max        if (arr[i] > max__):                         # max will become secondMax            secondMax = max__Â
            # Update the max            max__ = arr[i]Â
        # If current element is greater than         # secondMax but smaller than max        elif (arr[i] > secondMax):                         # Update the secondMax            secondMax = arr[i]Â
        # If current element is smaller than min        elif(arr[i] < min__):                         # min will become secondMin            secondMin = min__Â
            # Update the min            min__ = arr[i]Â
        # If current element is smaller than         # secondMin but greater than min        elif(arr[i] < secondMin):                         # Update the secondMin            secondMin = arr[i]         # Minimum of the two possible     # differences    diff = min(max__ - secondMin,                        secondMax - min__)    return diffÂ
# Driver codeif __name__ == '__main__':Â Â Â Â arr = [1, 2, 4, 3, 4]Â Â Â Â n = len(arr)Â Â Â Â print(findMinDifference(arr, n))Â
# This code is contributed by# Surendra_Gangwar |
C#
using System;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â // C# implementation of the approach public class GFG { Â
    // Function to return the minimum required difference     static int findMinDifference(int []arr, int n)     {         int min, secondMin, max, secondMax; Â
        min = secondMax = (arr[0] < arr[1]) ? arr[0] : arr[1];         max = secondMin = (arr[0] < arr[1]) ? arr[1] : arr[0]; Â
        for (int i = 2; i < n; i++) { Â
            // If current element is greater than max             if (arr[i] > max) { Â
                // max will become secondMax                 secondMax = max; Â
                // Update the max                 max = arr[i];             } Â
            // If current element is greater than secondMax             // but smaller than max             else if (arr[i] > secondMax) { Â
                // Update the secondMax                 secondMax = arr[i];             } Â
            // If current element is smaller than min             else if (arr[i] < min) { Â
                // min will become secondMin                 secondMin = min; Â
                // Update the min                 min = arr[i];             } Â
            // If current element is smaller than secondMin             // but greater than min             else if (arr[i] < secondMin) { Â
                // Update the secondMin                 secondMin = arr[i];             }         } Â
        // Minimum of the two possible differences         int diff = Math.Min(max - secondMin, secondMax - min); Â
        return diff;     } Â
    // Driver code     public static void Main()     {         int []arr = { 1, 2, 4, 3, 4 };         int n = arr.Length; Â
        Console.WriteLine(findMinDifference(arr, n));     } } // This code is contributed by 29AjayKumar |
PHP
<?php// PHP implementation of the approachÂ
// Function to return the minimum// required differencefunction findMinDifference($arr, $n){Â
    $min__ = $secondMax = ($arr[0] < $arr[1]) ?                            $arr[0] : $arr[1];    $max__ = $secondMin = ($arr[0] < $arr[1]) ?                            $arr[1] : $arr[0];Â
    for ($i = 2; $i < $n; $i++)    {        // If current element is greater than max        if ($arr[$i] > $max__)        {            // max will become secondMax            $secondMax = $max__;Â
            // Update the max            $max__ = $arr[$i];        }Â
        // If current element is greater than secondMax        // but smaller than max        else if ($arr[$i] > $secondMax)        {Â
            // Update the secondMax            $secondMax = $arr[$i];        }Â
        // If current element is smaller than min        else if ($arr[$i] < $min__)         {Â
            // min will become secondMin            $secondMin = $min__;Â
            // Update the min            $min__ = $arr[$i];        }Â
        // If current element is smaller than secondMin        // but greater than min        else if ($arr[$i] < $secondMin)         {                             // Update the secondMin            $secondMin = $arr[$i];        }    }Â
    // Minimum of the two possible differences    $diff = min($max__ - $secondMin,                          $secondMax - $min__);    return $diff;}Â
// Driver code$arr = array( 1, 2, 4, 3, 4 );$n = count($arr);print(findMinDifference($arr, $n));Â
// This code is contributed by mits?> |
Javascript
<script>Â
    // Javascript implementation of the approach          // Function to return the minimum required difference    function findMinDifference(arr, n)    {        let min__, secondMin, max__, secondMax;              min__ = secondMax = (arr[0] < arr[1]) ? arr[0] : arr[1];        max__ = secondMin = (arr[0] < arr[1]) ? arr[1] : arr[0];              for (let i = 2; i < n; i++)        {            // If current element is greater than max            if (arr[i] > max__)            {                // max will become secondMax                secondMax = max__;                      // Update the max                max__ = arr[i];            }                  // If current element is greater than secondMax            // but smaller than max            else if (arr[i] > secondMax)            {                      // Update the secondMax                secondMax = arr[i];            }                  // If current element is smaller than min            else if (arr[i] < min__)             {                      // min will become secondMin                secondMin = min__;                      // Update the min                min__ = arr[i];            }                  // If current element is smaller than secondMin            // but greater than min            else if (arr[i] < secondMin) {                                      // Update the secondMin                secondMin = arr[i];            }        }              // Minimum of the two possible differences        let diff = Math.min(max__ - secondMin, secondMax - min__);        return diff;    }           let arr = [ 1, 2, 4, 3, 4 ];    let n = arr.length;    document.write(findMinDifference(arr, n));      </script> |
2
Complexity Analysis:
- Time Complexity: O(n), to traverse an array of size n
- Auxiliary Space: O(1), as no extra space is used
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



