forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaximum-of-absolute-value-expression.cpp
29 lines (28 loc) · 1.26 KB
/
maximum-of-absolute-value-expression.cpp
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
27
28
29
// Time: O(n)
// Space: O(1)
class Solution {
public:
int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {
// 1. max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for i > j)
// = max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for j > i)
// 2. for i > j:
// (|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j|)
// >= c1*(arr1[i]-arr1[j]) + c2*(arr2[i]-arr2[j]) + i-j for c1 in (1, -1), c2 in (1, -1)
// = (c1*arr1[i]+c2*arr2[i]+i) - (c1*arr1[j]+c2*arr2[j]+j) for c1 in (1, -1), c2 in (1, -1)
// 1 + 2 => max(|arr1[i]-arr1[j]| + |arr2[i]-arr2[j]| + |i-j| for i != j)
// = max((c1*arr1[i]+c2*arr2[i]+i) - (c1*arr1[j]+c2*arr2[j]+j)
// for c1 in (1, -1), c2 in (1, -1) for i > j)
int result = 0;
for (const auto& c1 : {1, -1}) {
for (const auto& c2 : {1, -1}) {
int min_prev = c1 * arr1[0] + c2 * arr2[0] + 0;
for (int i = 1; i < arr1.size(); ++i) {
const auto& curr = c1 * arr1[i] + c2 * arr2[i] + i;
result = max(result, curr - min_prev);
min_prev = min(min_prev, curr);
}
}
}
return result;
}
};