Minimize the maximum minimum difference after one removal from array | C ++ implementation of the approach ; Function to return the minimum required difference ; If current element is greater than max ; max will become secondMax ; Update the max ; If current element is greater than secondMax but smaller than max ; Update the secondMax ; If current element is smaller than min ; min will become secondMin ; Update the min ; If current element is smaller than secondMin but greater than min ; Update the secondMin ; Minimum of the two possible differences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ( arr [ i ] > max__ ) { secondMax = max__ ; max__ = arr [ i ] ; } else if ( arr [ i ] > secondMax ) { secondMax = arr [ i ] ; } else if ( arr [ i ] < min__ ) { secondMin = min__ ; min__ = arr [ i ] ; } else if ( arr [ i ] < secondMin ) { secondMin = arr [ i ] ; } } int diff = min ( max__ - secondMin , secondMax - min__ ) ; return diff ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( findMinDifference ( arr , n ) ) ; }