Problem Description
Given two arrays of integers arr1 and arr2 of equal length, find the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| for all valid indices 0 <= i, j < arr1.length.
Key Insights
- The expression involves absolute differences over three terms: two from the arrays and one from the indices.
- By considering different sign combinations, we can transform the expression into four different linear forms.
- Tracking the maximum and minimum values for each transformed expression allows for a direct calculation of the answer.
- Only one pass through the arrays is necessary, resulting in an efficient O(n) solution.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We transform the original expression into four forms to account for different sign combinations:
- T1(i) = arr1[i] + arr2[i] + i
- T2(i) = arr1[i] + arr2[i] - i
- T3(i) = arr1[i] - arr2[i] + i
- T4(i) = arr1[i] - arr2[i] - i
For each transformation, iterate through the arrays keeping track of maximum and minimum values. The maximum difference for a transformed sequence is given by (max - min). The overall answer is the maximum among these four differences. This greedy approach avoids a double loop and efficiently computes the result in one pass.