Saturday, 16 Oct 2021

# Maximum value of X such that difference between any array element and X does not exceed K

Maximum value of X such that difference between any array element and X does not exceed KGiven an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum possible integer X, such that the absolute difference between any array element and X is at most K. If no such value of X exists, then print “-1”.Examples:Input: arr[] = {6, 4, 8, 5}, K = 2Output: 6Explanation: Considering X to be 6, the absolute difference between every array element and X(= 6) is at most K (= 2), as illustrated below:Absolute difference between arr(= 6) and X(= 6) = |6 – 6| = 0.Absolute difference between arr(= 4) and X(= 6) = |4 – 6| = 2.Absolute difference between arr(= 8) and X(= 6) = |8 – 6| = 2.Absolute difference between arr(= 5) and X(= 6) = |5 – 6| = 1.Input: arr[] = {1, 2, 5}, K = 2Output: 3Approach: The given problem can be solved based on the following observations:Considering array elements to be arr[i], the value of |arr[i] – X| must be at most K.If arr[i] > X, then X ≤ (arr[i] – K). Otherwise, X ≤ (arr[i] + K).From the above two equations, the maximum value of X must be the sum of minimum value of arr[i] and K.Follow the steps below to solve the problem:Below is the implementation of the above approach:C++  #include 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