Maximum of Absolute Value Expression - Problem

Given two arrays of integers arr1 and arr2 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.

Input & Output

Example 1 — Basic Case
$ Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13
💡 Note: Maximum occurs at i=3, j=0: |4-1| + |6-(-1)| + |3-0| = 3 + 7 + 3 = 13
Example 2 — Small Array
$ Input: arr1 = [1,-2], arr2 = [-1,4]
Output: 9
💡 Note: Only two elements: |1-(-2)| + |-1-4| + |0-1| = 3 + 5 + 1 = 9
Example 3 — Same Values
$ Input: arr1 = [1,1,1], arr2 = [2,2,2]
Output: 2
💡 Note: Arrays have same values, maximum comes from index difference: |1-1| + |2-2| + |0-2| = 0 + 0 + 2 = 2

Constraints

  • 2 ≤ arr1.length == arr2.length ≤ 40000
  • -106 ≤ arr1[i], arr2[i] ≤ 106

Visualization

Tap to expand
Maximum of Absolute Value Expression INPUT arr1 = [1, 2, 3, 4] 1 2 3 4 i=0 i=1 i=2 i=3 arr2 = [-1, 4, 5, 6] -1 4 5 6 Expression to Maximize: |arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| Length: n = 4 Find max over all i,j pairs where 0 <= i, j < n ALGORITHM STEPS 1 Transform Expression Remove absolute values with 4 sign combinations (+/-) 2 Define 4 Cases For signs (p,q) in {+1,-1}: f(i) = p*arr1[i]+q*arr2[i]+i 3 Compute Each Case Result = max(f) - min(f) for each sign combination 4 Take Maximum Return max across all 4 cases Case Calculations: (+,+): [0,7,10,13] max-min=13 (+,-): [2,-1,-0,-1] max-min=3 (-,+): [-2,3,4,5] max-min=7 (-,-): [0,-5,-6,-7] max-min=7 Maximum = 13 FINAL RESULT Output 13 Optimal: i=0, j=3 Verification: |arr1[0]-arr1[3]| = |1-4| = 3 |arr2[0]-arr2[3]| = |-1-6| = 7 |0-3| = 3 Total: 3 + 7 + 3 = 13 [OK] Complexity Time: O(n) - single pass Space: O(1) - constant OPTIMIZED! Key Insight: The Manhattan distance formula with absolute values can be decomposed into 4 cases by considering all sign combinations. For each case, the expression becomes (p*arr1[i] + q*arr2[i] + i) - (p*arr1[j] + q*arr2[j] + j). Maximum is achieved by taking max(f) - min(f) for each case, avoiding O(n^2) brute force. TutorialsPoint - Maximum of Absolute Value Expression | Mathematical Optimization Approach
Asked in
Google 25 Facebook 18 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen