Formatted question description: https://leetcode.ca/all/1131.html

1131. Maximum of Absolute Value Expression

Level

Medium

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

Solution

For the expression |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|, there are 4 cases as follows.

  1. arr1[i] - arr1[j] >= 0 and arr2[i] - arr2[j] >= 0. The expression is equivalent to (arr1[i] + arr2[i]) - (arr1[j] + arr2[j]) + |i - j|.
  2. arr1[i] - arr1[j] >= 0 and arr2[i] - arr2[j] < 0. The expression is equivalent to (arr1[i] - arr2[i]) - (arr1[j] - arr2[j]) + |i - j|.
  3. arr1[i] - arr1[j] < 0 and arr2[i] - arr2[j] >= 0. The expression is equivalent to (-arr1[i] + arr2[i]) - (-arr1[j] + arr2[j]) + |i - j|.
  4. arr1[i] - arr1[j] < 0 and arr2[i] - arr2[j] < 0. The expression is equivalent to (-arr1[i] - arr2[i]) - (-arr1[j] - arr2[j]) + |i - j|.

Each case can be represented in the form arr[i] - arr[j] + |i - j|. In the form, either i >= j or i < j.

So loop over all possible cases and find the maximum value.

class Solution {
    public int maxAbsValExpr(int[] arr1, int[] arr2) {
        int length = arr1.length;
        int[][] nums = new int[4][length];
        for (int i = 0; i < length; i++) {
            nums[0][i] = arr1[i] + arr2[i];
            nums[1][i] = arr1[i] - arr2[i];
            nums[2][i] = -arr1[i] + arr2[i];
            nums[3][i] = -arr1[i] - arr2[i];
        }
        int maxValue = 0;
        for (int i = 0; i < 4; i++) {
            int curValue = maxValExpr(nums[i]);
            maxValue = Math.max(maxValue, curValue);
        }
        return maxValue;
    }

    public int maxValExpr(int[] arr) {
        int length = arr.length;
        int[] arr1 = new int[length];
        int[] arr2 = new int[length];
        for (int i = 0; i < length; i++) {
            arr1[i] = i + arr[i];
            arr2[i] = i - arr[i];
        }
        int maxDifference1 = maxDifference(arr1);
        int maxDifference2 = maxDifference(arr2);
        return Math.max(maxDifference1, maxDifference2);
    }

    public int maxDifference(int[] arr) {
        int min = Integer.MAX_VALUE;
        int length = arr.length;
        int maxDifference = Integer.MIN_VALUE;
        for (int i = 0; i < length; i++) {
            if (arr[i] < min)
                min = arr[i];
            else if (arr[i] - min > maxDifference)
                maxDifference = arr[i] - min;
        }
        return maxDifference;
    }
}

All Problems

All Solutions