Description
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
Solutions
Solution 1: Mathematics + Enumeration
Let's denote xi = arr1[i], yi = arr2[i]. Since the size relationship between i and j does not affect the value of the expression, we can assume i \ge j. Then the expression can be transformed into:
| xi - xj | + | yi - yj | + i - j = max \begin{cases} (xi + yi) - (xj + yj) \ (xi - yi) - (xj - yj) \ (-xi + yi) - (-xj + yj) \ (-xi - yi) - (-xj - yj) \end{cases} + i - j\
= max \begin{cases} (xi + yi + i) - (xj + yj + j) \ (xi - yi + i) - (xj - yj + j) \ (-xi + yi + i) - (-xj + yj + j) \ (-xi - yi + i) - (-xj - yj + j) \end{cases}
Therefore, we just need to find the maximum value mx and the minimum value mi of a × xi + b × yi + i, where a, b ∈ {-1, 1}. The answer is the maximum value among all mx - mi.
The time complexity is O(n), where n is the length of the array. The space complexity is O(1).
Similar problems:
PythonJavaC++GoTypeScript
class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: dirs = (1, -1, -1, 1, 1) ans = -inf for a, b in pairwise(dirs): mx, mi = -inf, inf for i, (x, y) in enumerate(zip(arr1, arr2)): mx = max(mx, a * x + b * y + i) mi = min(mi, a * x + b * y + i) ans = max(ans, mx - mi) return ans(code-box)
