Skip to content

1131. Maximum of Absolute Value Expression

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {
    const int n = arr1.size();
    vector<int> a(n);
    vector<int> b(n);
    vector<int> c(n);
    vector<int> d(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;
    }

    return max(max(diff(a), diff(b)), max(diff(c), diff(d)));
  }

 private:
  int diff(vector<int>& nums) {
    return ranges::max(nums) - ranges::min(nums);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int maxAbsValExpr(int[] arr1, int[] arr2) {
    final int n = arr1.length;
    int[] a = new int[n];
    int[] b = new int[n];
    int[] c = new int[n];
    int[] 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;
    }

    return Math.max(Math.max(diff(a), diff(b)), Math.max(diff(c), diff(d)));
  }

  private int diff(int[] nums) {
    final int mn = Arrays.stream(nums).min().getAsInt();
    final int mx = Arrays.stream(nums).max().getAsInt();
    return mx - mn;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def maxAbsValExpr(self, arr1: list[int], arr2: list[int]) -> int:
    n = len(arr1)
    a = [arr1[i] + arr2[i] + i for i in range(n)]
    b = [arr1[i] + arr2[i] - i for i in range(n)]
    c = [arr1[i] - arr2[i] + i for i in range(n)]
    d = [arr1[i] - arr2[i] - i for i in range(n)]
    return max(map(lambda x: max(x) - min(x), (a, b, c, d)))