Algorithm


Problem Name: 1131. Maximum of Absolute Value Expression

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

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int maxAbsValExpr(int[] arr1, int[] arr2) {
    int res = 0;
    int n = arr1.length;
    int[] dirs = {-1,1};
    for (int dir1 : dirs) {
      for (int dir2 : dirs) {
        int closest = dir1 * arr1[0] + dir2 * arr2[0] + 0;
        for (int i = 1; i  <  n; ++i) {
          int cur = dir1 * arr1[i] + dir2 * arr2[i] + i;
          res = Math.max(res, cur - closest);
          closest = Math.min(closest, cur);
        }
      }
    }
    return res;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
arr1 = [1,2,3,4], arr2 = [-1,4,5,6]

Output

x
+
cmd
13

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
        l1, l2 ,l3, l4 = [], [], [], []
        for i in range(len(arr1)):
            l1 += [arr1[i]+arr2[i]+i]
            l2 += [arr1[i]-arr2[i]+i]
            l3 += [-arr1[i]+arr2[i]+i]
            l4 += [-arr1[i]-arr2[i]+i]
        res = []
        res += [max(l1)-min(l1)]
        res += [max(l2) -min(l2)]
        res += [max(l3)-min(l3)]
        res += [max(l4)-min(l4)]
        return max(res)
Copy The Code & Try With Live Editor

Input

x
+
cmd
arr1 = [1,2,3,4], arr2 = [-1,4,5,6]

Output

x
+
cmd
13
Advertisements

Demonstration


Previous
#1130 Leetcode Minimum Cost Tree From Leaf Values Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1137 Leetcode N-th Tribonacci Number Solution in C, C++, Java, JavaScript, Python, C# Leetcode