Maximum of Absolute Value Expression Problem
Description
LeetCode Problem 1131.
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
Constraints:
2 <= arr1.length == arr2.length <= 40000-10^6 <= arr1[i], arr2[i] <= 10^6
Solution
Approach: Try the Four Sign Patterns
Checking every pair is O(n2), too slow for 40000 elements. The absolute values are what make the expression hard, so get rid of them. Write x = arr1, y = arr2, and assume i >= j (the expression is symmetric, so this loses nothing). Then |i - j| = i - j, and for the other two terms |t| = max(t, -t), so
|x_i - x_j| + |y_i - y_j| + (i - j) = max over a, b in {1, -1} of (a*x_i + b*y_i + i) - (a*x_j + b*y_j + j)
For a fixed sign pair (a, b), define v_k = a*x_k + b*y_k + k. The best value of v_i - v_j is simply max(v) - min(v). If the maximum sits at a smaller index than the minimum, that pair has i < j, which we assumed away, but the value is still at most the true expression for that pair, so it can never push the answer too high.
Compute max(v) - min(v) for each of the four sign patterns and return the largest.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
best = 0
# With signs a, b fixed, the expression is (a*x_i + b*y_i + i) - (a*x_j + b*y_j + j) for some i >= j.
for a, b in ((1, 1), (1, -1), (-1, 1), (-1, -1)):
values = [a * x + b * y + i for i, (x, y) in enumerate(zip(arr1, arr2))]
best = max(best, max(values) - min(values))
return best