Maximum value of X such that difference between any array element and X does not exceed K | 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
function maximumNumber ( arr , N , K ) { let minimum = Math . min ( ... arr ) let ans = minimum + K ; for ( let i = 0 ; i < N ; i ++ ) { if ( Math . abs ( arr [ i ] - ans ) > K ) { ans = - 1 ; break ; } } document . write ( ans ) } let arr = [ 1 , 2 , 5 ] let K = 2 let N = arr . length maximumNumber ( arr , N , K ) ;