Maximum Absolute Difference

Last updated: 29th Aug, 2020

       

Problem Statment

You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j) for all 1 ≤ i, j ≤ N.

f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.

Example 1:

A=[1, 3, -1]

f(1, 1) = f(2, 2) = f(3, 3) = 0
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5

Approach:

f(i, j) = |A[i] - A[j]| + |i - j| can be written in 4 ways (Since we are looking at max value, we don’t even care if the value becomes negative as long as we are also covering the max value in some way).

  Case 1 : (A[i] + i) - (A[j] + j)
  Case 2 : -(A[i] - i) + (A[j] - j)
  Case 3 : (A[i] - i) - (A[j] - j)
  Case 4 : (-A[i] - i) + (A[j] + j) = -(A[i] + i) + (A[j] + j)

Note that case 1 and 4 are equivalent and so are case 2 and 3.
We can construct two arrays with values: A[i] + i and A[i] - i. Then, for above 2 distinct cases, we find the maximum value possible. For that, we just have to store minimum and maximum values of expressions A[i] + i and A[i] - i for all i.

C++ Code

// Method to return the required Maximum absolute difference
int maxArr(vector<int> a) 
{
    // length of given vector
    int n = a.size();

    // declaring two vectors to store A[i] + i and A[i] - i
    vector<int> a1(n), a2(n);

    // storing the required values in a1 and a2
    for(int i=0; i<n; i++) {
        a1[i] = a[i] + i;
        a2[i] = a[i] - i;
    }

    // max and min values of a1 (A[i] + i)
    int max_of_a1 = *max_element(a1.begin(), a1.end());
    int min_of_a1 = *min_element(a1.begin(), a1.end());

    // max and min values of a2 (A[i] - i)
    int max_of_a2 = *max_element(a2.begin(), a2.end());
    int min_of_a2 = *min_element(a2.begin(), a2.end());

    // return the maximum value possible
    return max(max_of_a1 - min_of_a1, max_of_a2- min_of_a2);
}

                    


Python Code

class Solution:

    def maxArr(self, a):
        n = len(a)
        a1 = [a[i] + i for i in range(n)]
        a2 = [a[i] - i for i in range(n)]
        return max(max(a1)-min(a1), max(a2)-min(a2))