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
using System ; using System . Collections . Generic ; class GFG { static void maximumNumber ( int [ ] arr , int N , int K ) { int mn = 100000000 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < mn ) mn = arr [ i ] ; } int ans = mn + K ; for ( int i = 0 ; i < N ; i ++ ) { if ( Math . Abs ( arr [ i ] - ans ) > K ) { ans = - 1 ; break ; } } Console . Write ( ans ) ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 5 } ; int K = 2 ; int N = arr . Length ; maximumNumber ( arr , N , K ) ; } }