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
< ? php function 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 ( $ 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 ] ; } } $ diff = min ( $ max__ - $ secondMin , $ secondMax - $ min__ ) ; return $ diff ; } $ arr = array ( 1 , 2 , 4 , 3 , 4 ) ; $ n = count ( $ arr ) ; print ( findMinDifference ( $ arr , $ n ) ) ; ? >