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 integersa and
b to be their absolute difference |a-b|. Your task is to find the maximum distance.
Example 1:
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
marrays will be in the range of [2, 10000]. - The integers in the
marrays will be in the range of [-10000, 10000].
public class Solution {
public int maxDistance(List<List<Integer>> arrays) {
}
}解决方法:
public int maxDistance(List<List<Integer>> arrays) {
int min = arrays.get(0).get(0);
int max = arrays.get(0).get(arrays.get(0).size()-1);
int result = Integer.MIN_VALUE;
for(int i=1; i<arrays.size(); i++){
int curmax = arrays.get(i).get(arrays.get(i).size()-1);
int curmin = arrays.get(i).get(0);
result = Math.max(result, Math.abs(max - curmin));
result = Math.max(result, Math.abs(min - curmax));
max = Math.max(max, curmax);
min = Math.min(min, curmin);
}
return result;
}
本文介绍了一种算法,用于从多个已排序数组中选取两个整数并计算它们之间的最大绝对差值。通过一次遍历所有数组并跟踪每个数组的最大最小值,可以高效地找到最大距离。
1678





