class Solution:
def maxAbsValExpr(self, arr1, arr2):
res = 0
n = len(arr1)
for p, q in [(1,1), (1,-1), (-1,1), (-1,-1)]:
max_val = float('-inf')
min_val = float('inf')
for i in range(n):
value = p*arr1[i] + q*arr2[i] + i
max_val = max(max_val, value)
min_val = min(min_val, value)
res = max(res, max_val - min_val)
return res
class Solution {
public:
int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {
int res = 0, n = arr1.size();
int signs[2] = {1, -1};
for (int p : signs) {
for (int q : signs) {
int maxVal = INT_MIN, minVal = INT_MAX;
for (int i = 0; i < n; ++i) {
int value = p*arr1[i] + q*arr2[i] + i;
maxVal = max(maxVal, value);
minVal = min(minVal, value);
}
res = max(res, maxVal - minVal);
}
}
return res;
}
};
class Solution {
public int maxAbsValExpr(int[] arr1, int[] arr2) {
int res = 0, n = arr1.length;
int[] signs = {1, -1};
for (int p : signs) {
for (int q : signs) {
int maxVal = Integer.MIN_VALUE, minVal = Integer.MAX_VALUE;
for (int i = 0; i < n; ++i) {
int value = p * arr1[i] + q * arr2[i] + i;
maxVal = Math.max(maxVal, value);
minVal = Math.min(minVal, value);
}
res = Math.max(res, maxVal - minVal);
}
}
return res;
}
}
var maxAbsValExpr = function(arr1, arr2) {
let res = 0, n = arr1.length;
let signs = [1, -1];
for (let p of signs) {
for (let q of signs) {
let maxVal = -Infinity, minVal = Infinity;
for (let i = 0; i < n; ++i) {
let value = p * arr1[i] + q * arr2[i] + i;
maxVal = Math.max(maxVal, value);
minVal = Math.min(minVal, value);
}
res = Math.max(res, maxVal - minVal);
}
}
return res;
};
arr1
and arr2
, both of length n
, you are asked to find the maximum value of the following expression for all pairs of indices i
and j
(where 0 ≤ i, j < n
):
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
n
can be large (up to 40,000). Each index can be paired with any other (including itself), and the arrays may contain both positive and negative integers.
i
, j
), calculating the expression, and keeping track of the maximum. This brute-force approach would involve O(n^2)
computations, which is not feasible for large arrays.
x
and y
, |x - y| = max(x - y, y - x)
.|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
, we can expand it by considering all sign combinations.|x - y| = |y - x|
, only 4 unique combinations matter.(p, q)
where p, q ∈ {1, -1}
, compute value = p*arr1[i] + q*arr2[i] + i
for all i
.value
across all i
.max_value - min_value
.O(n)
, since each combination only requires a single pass through the arrays.
arr1 = [1, 2, 3, 4]
and arr2 = [-1, 4, 5, 6]
.
(p=1, q=1)
:
arr1[i] + arr2[i] + i
for each i
:
(1, -1)
:
(-1, 1)
:
(-1, -1)
:
13
.
O(n^2)
time, since every pair of indices is checked. Space is O(1)
(ignoring input).O(n)
time, since for each of the 4 sign combinations, we scan the arrays once. Space is O(1)
extra (just variables for min/max).