Find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | Function that returns the second largest element in the array if exists , else 0 ; There must be at least two elements ; To store the maximum and the second maximum element from the array ; If current element is greater than first then update both first and second ; If arr [ i ] is in between first and second then update second ; No second maximum found ; Driver code
< ? php function getMaxValue ( $ arr , $ arr_size ) { if ( $ arr_size < 2 ) { return 0 ; } $ first = $ second = - ( PHP_INT_MAX - 1 ) ; for ( $ i = 0 ; $ i < $ arr_size ; $ i ++ ) { if ( $ arr [ $ i ] > $ first ) { $ second = $ first ; $ first = $ arr [ $ i ] ; } else if ( $ arr [ $ i ] > $ second && $ arr [ $ i ] != $ first ) $ second = $ arr [ $ i ] ; } if ( $ second == - ( PHP_INT_MAX - 1 ) ) return 0 ; else return $ second ; } $ arr = array ( 4 , 5 , 1 , 8 ) ; $ n = count ( $ arr ) ; echo getMaxValue ( $ arr , $ n ) ; ? >