Maximum of Absolute Value Expression LeetCode Problem
Given two arrays of integers with equal lengths, return the maximum value of:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length.
Example 1:
Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
Example 2:
Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20
Deriving the Four Cases
We consider all possible combinations of signs for the expression:
(arr1[i]−arr1[j])+(arr2[i]−arr2[j])+(i−j)
To handle absolute values, we expand this expression into four possible cases:
Case 1: arr1[i]>arr1[j] & arr2[i]>arr2[j]
(arr1[i]+arr2[i]+i)−(arr1[j]+arr2[j]+j)
Case 2:arr1[i]>arr1[j] & arr2[i]<arr2[j]
(arr1[i]-arr2[i]+i)−(arr1[j]-arr2[j]+j)
Case 3::arr1[i]<arr1[j] & arr2[j]>arr2[j]
(arr2[j]- arr1[i]+i)−(arr2[j]- arr1[j]+j)
Case 4:arr1[i]<arr1[j] & arr2[i]<arr2[j]
(i-arr1[i]−arr2[i])−(j-arr1[j]−arr2[j])
Both arr2 and i contribute negatively.
Why These Four Cases?
Since |X - Y| means X - Y or Y - X, we account for all positive and negative variations.
Instead of brute-force checking all pairs (i, j), we realize that maximizing each expression is equivalent to:
max(expression)−min(expression)
This allows us to optimize our approach.
Final Algorithm
Compute four transformed arrays based on the four cases above.
For each transformed array:
Track minimum and maximum values.
Compute max - min.
Return the maximum value among the four cases.
Comments
Post a Comment