Home >> Programming Questions >> Maximum Absolute Difference Maximum Absolute Difference InterviewBit Solution You are given an array of N integers, A 1 , A2, …, A N . 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 the absolute value of x. For example , 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 So, we return 5. Solution Here function f(i, j) = |A[i] - A[j]| + |i-j] can be written in four ways - (A[i] + i) - (A[j] + j) -(A[i] - i) + (A[j] - j) (A[i] - i) - (A[j] - j) (-A[i] - i) + (A[j] + j) = -(A[i] + i) + (A[j] + j) we just have to store minimum and maximum values of expressions A[i] + i and A[i] - i for all i. Java Code:: 1 2 3 4 5...
Comments
Post a Comment