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
25
26
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) {
    const int min = *min_element(begin(nums), end(nums));
    const int max = *max_element(begin(nums), end(nums));
    return max - min;
  }
};
 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 min = Arrays.stream(nums).min().getAsInt();
    final int max = Arrays.stream(nums).max().getAsInt();
    return max - min;
  }
}
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)))