[LeetCode] Maximum of Absolute Value Expression

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int helper(vector<int>& A, vector<int>& B, int p, int q) {
auto func = [&](int i) {
return p * A[i] + q * B[i] + i;
};
int mi = func(0), ma = func(0), n = A.size();
for(int i = 1; i < n; i++) {
mi = min(mi, func(i));
ma = max(ma, func(i));
}
return ma - mi;
}
public:
int maxAbsValExpr(vector<int>& A, vector<int>& B) {
int res = INT_MIN;
res = max(res, helper(A,B,1,1));
res = max(res, helper(A,B,1,-1));
res = max(res, helper(A,B,-1,-1));
res = max(res, helper(A,B,-1,1));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/05/PS/LeetCode/maximum-of-absolute-value-expression/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.