Maximum of Absolute Value Expression

LeetCode Q 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

Solution

For equation |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|, if we remove the absolute value signal, then it has four cases regarding i>j. They are,

  • (arr1[i] + arr2[i] + i) - (arr1[j] + arr2[j] + j);
  • (arr1[i] - arr2[i] + i) - (arr1[j] - arr2[j] + j);
  • (-arr1[i] + arr2[i] + i) - (-arr1[j] + arr2[j] + j);
  • (-arr1[i] - arr2[i] + i) - (-arr1[i] - arr2[i] + j);

So, we can define four arrays,

  • a: arr1[i] + arr2[i] + i;
  • b: arr1[i] - arr2[i] + i;
  • c: -arr1[i] + arr2[i] + i;
  • d: -arr1[i] - arr2[i] + i;

Find the maximum and minimum value in each array, get 4 candidates, and choose the largest one as the result.

Code:

public int maxAbsValExpr(int[] arr1, int[] arr2) {
  int n = arr1.length;
  int[] a = new int[n], b = new int[n], c = new int[n], d = new int[n];
  
  for (int i = 0; i < n; i++) {
    a[i] = arr1[i] + arr2[i] + i;
    b[i] = arr1[i] - arr2[i] + i;
    c[i] = -arr1[i] + arr2[i] + i;
    d[i] = -arr1[i] - arr2[i] + i;
  }

  int res = getMax(a) - getMin(a);
  res = Math.max(getMax(b) - getMin(b), res);
  res = Math.max(getMax(c) - getMin(c), res);
  res = Math.max(getMax(d) - getMin(d), res);
  
  return res;
}

private int getMax(int[] arr) {
  int res = arr[0];
  for (int i = 1; i < arr.length; i++) res = Math.max(arr[i], res);
  return res;
}

private int getMin(int[] arr) {
  int res = arr[0];
  for (int i = 1; i < arr.length; i++) res = Math.min(arr[i], res);
  return res;

   Reprint policy


《Maximum of Absolute Value Expression》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC