Find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxValue ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { return 0 ; } first = second = INT_MIN ; 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 == INT_MIN ) return 0 ; else return second ; } int main ( ) { int arr [ ] = { 4 , 5 , 1 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMaxValue ( arr , n ) ; return 0 ; }