Remove exactly one element from the array such that max | C ++ implementation of the above approach ; function to calculate max - min ; There should be at - least two elements ; To store first and second minimums ; To store first and second maximums ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_min ( int a [ ] , int n ) { if ( n <= 1 ) return INT_MAX ; int f_min = a [ 0 ] , s_min = INT_MAX ; int f_max = a [ 0 ] , s_max = INT_MIN ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] <= f_min ) { s_min = f_min ; f_min = a [ i ] ; } else if ( a [ i ] < s_min ) { s_min = a [ i ] ; } if ( a [ i ] >= f_max ) { s_max = f_max ; f_max = a [ i ] ; } else if ( a [ i ] > s_max ) { s_max = a [ i ] ; } } return min ( ( f_max - s_min ) , ( s_max - f_min ) ) ; } int main ( ) { int a [ ] = { 1 , 3 , 3 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << max_min ( a , n ) ; return 0 ; }