# 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`

`arr1[i] - arr1[j] + arr2[i] - arr2[j] + i - j`

`arr1[i] - arr1[j] + arr2[i] - arr2[j] - i + j`

`arr1[i] - arr1[j] - arr2[i] + arr2[j] + i - j`

`arr1[i] - arr1[j] - arr2[i] + arr2[j] - i + j`

`- arr1[i] + arr1[j] + arr2[i] - arr2[j] + i - j`

`- arr1[i] + arr1[j] + arr2[i] - arr2[j] - i + j`

`- arr1[i] + arr1[j] - arr2[i] + arr2[j] + i - j`

`- arr1[i] + arr1[j] - arr2[i] + arr2[j] - i + 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[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[j] - arr2[j] + j)`

`- (arr1[i] + arr2[i] - i) + (arr1[j] + arr2[j] - j)`

`- (arr1[i] + arr2[i] + i) + (arr1[j] + arr2[j] + j)`

``````class Solution {
public:
int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {
int n = arr1.size();
vector<int> sum1(n), sum2(n), diff1(n), diff2(n);
for (int i = 0; i < n; ++i) {
sum1[i] = arr1[i] + arr2[i] + i;
sum2[i] = arr1[i] + arr2[i] - i;
diff1[i] = arr1[i] - arr2[i] + i;
diff2[i] = arr1[i] - arr2[i] - i;
}
return max(max(helper(sum1), helper(sum2)), max(helper(diff1), helper(diff2)));
}
int helper(vector<int>& arr) {
int mx = arr[0], mn = arr[0];
for (int num : arr) {
mx = max(mx, num);
mn = min(mn, num);
}
return mx - mn;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1131

https://leetcode.com/problems/maximum-of-absolute-value-expression/

https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/339968/JavaC%2B%2BPython-Maximum-Manhattan-Distance

https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/340075/c%2B%2B-beats-100-(both-time-and-memory)-with-algorithm-and-image

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation