Maximum value of X such that difference between any array element and X does not exceed K | C ++ program for the above approach ; Function to find maximum value of X such that | A [ i ] - X | a K ; Stores the smallest array element ; Store the possible value of X ; Traverse the array A [ ] ; If required criteria is not satisfied ; Update ans ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumNumber ( int arr [ ] , int N , int K ) { int minimum = * min_element ( arr , arr + N ) ; int ans = minimum + K ; for ( int i = 0 ; i < N ; i ++ ) { if ( abs ( arr [ i ] - ans ) > K ) { ans = -1 ; break ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumNumber ( arr , N , K ) ; return 0 ; }