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
function getMaxValue ( arr , arr_size ) { let i , first , second ; if ( arr_size < 2 ) { return 0 ; } first = second = Number . MIN_VALUE ; 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 == Number . MIN_VALUE ) { return 0 ; } else { return second ; } } let arr = [ 4 , 5 , 1 , 8 ] ; let n = arr . length ; document . write ( getMaxValue ( arr , n ) ) ;