Minimize the maximum minimum difference after one removal from array | 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
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 ( 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 ] ; } } 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 ) ) ;