1. 问题描述
You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j) for all 1 ≤ i, j ≤ N.
f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x.
For example,
A=[1, 3, -1]
f(1, 1) = f(2, 2) = f(3, 3) = 0
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5
So, we return 5.
求一个数组中的最大曼哈顿距离,要求时间复杂度为O(n).
曼哈顿距离定义:The distance between two points measured along axes at right angles. In a plane with p1 at (x1, y1) and p2 at (x2, y2), it is |x1 - x2| + |y1 - y2|.
2. 复杂度为O(n^2)的算法
public int maxArr1(ArrayList<Integer> A) {
int result, temp;
result = 0;
for (int i = 0; i < A.size(); i++) {
for (int j = i + 1; j < A.size(); j++) {
temp = Math.abs(A.get(j) - A.get(i)) + Math.abs(j - i);
if (result < temp)
result = temp;
}
}
return result;
}
3. 复杂度为O(n)算法
算法思路:
1). 在数组中找到以下的点:max(x[i]+y[i]), max(x[I]-y[I]),max(-x[i]+y[I]),max(-x[I]-y[I]).
2). 计算数组中的每个点的上述距离,并取最大的值。该算法以线性时间运行,因为只考虑4*N对点。
3). 我们可以首先固定一个点,如(x[k],y[k]), 并找到离该点最远的一个点。考虑任意的点(x[i], y[i]), 则按曼哈顿距离展开后,假设展开后为如下情形可知道:
x[I]+x[k]+y[I]+y[k] = (x[k]+y[k]) + x[I]+y[I];
其中第一部分为固定的,所以最大值即为后一部分的值。其他的三种情形亦然。
public int maxArr(ArrayList<Integer> A) {
int sz = A.size();
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
int max4 = Integer.MIN_VALUE;
int ans = Integer.MIN_VALUE;
for (int i = 0; i < sz; i++) {
max1 = Math.max(max1, A.get(i) + i);
max2 = Math.max(max2, -A.get(i) + i);
max3 = Math.max(max3, A.get(i) - i);
max4 = Math.max(max4, -A.get(i) - i);
}
for (int i = 0; i < sz; i++) {
ans = Math.max(ans, max1 - A.get(i) - i);
ans = Math.max(ans, max2 + A.get(i) - i);
ans = Math.max(ans, max3 - A.get(i) + i);
ans = Math.max(ans, max4 + A.get(i) + i);
}
return ans;
}