624. Maximum Distance in Arrays

Given m arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.

Example 1:

1
2
3
4
5
6
7
Input:
[[1,2,3],
[4,5],
[1,2,3]]
Output: 4
Explanation:
One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.

Note:

Each given array will have at least 1 number. There will be at least two non-empty arrays.
The total number of the integers in all the m arrays will be in the range of [2, 10000].
The integers in the m arrays will be in the range of [-10000, 10000].

解法1: O(NM)

Maintain global min and max calculated from previous arrays and compare current min, max wrt to the global ones.
Results should be in Max(res, abs(global_min - current_max)) and Max(res, abs(global_max - current_min))
C++

1

Java

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
30
31
public class Solution {
public int maxDistance(List<List<Integer>> arrays) {
int res = Integer.MIN_VALUE;
int amin = Integer.MAX_VALUE;
int amax = Integer.MIN_VALUE;
for (int i = 0; i < arrays.get(0).size(); i++) {
amin = Math.min(amin, arrays.get(0).get(i));
amax = Math.max(amax, arrays.get(0).get(i));
}
for (int i = 1; i < arrays.size(); i++) {
// get min and max from each array
int cmin = Integer.MAX_VALUE;
int cmax = Integer.MIN_VALUE;
for (int j = 0; j < arrays.get(i).size(); j++) {
cmin = Math.min(cmin, arrays.get(i).get(j));
cmax = Math.max(cmax, arrays.get(i).get(j));
res = Math.max(res, Math.abs(amin - cmax));
res = Math.max(res, Math.abs(amax - cmin));
}
amin = Math.min(cmin, amin);
amax = Math.max(cmax, amax);
}
return res;
}
}