Maximum value of X such that difference between any array element and X does not exceed K | Java 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
import java . util . * ; class GFG { static void maximumNumber ( int arr [ ] , int N , int K ) { int minimum = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; int ans = minimum + K ; for ( int i = 0 ; i < N ; i ++ ) { if ( Math . abs ( arr [ i ] - ans ) > K ) { ans = - 1 ; break ; } } System . out . print ( ans ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 5 } ; int K = 2 ; int N = arr . length ; maximumNumber ( arr , N , K ) ; } }