# 624. Maximum Distance in Arrays 数组列表中的最大距离

@TOC

## # 题目描述

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:

``````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:

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

## # 解题方法

### # 大根堆+小根堆

C++代码如下：

``````class Solution {
public:
int maxDistance(vector<vector<int>>& arrays) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> mins;
priority_queue<pair<int, int>> maxs;
for (int i = 0; i < arrays.size(); ++i) {
auto arr = arrays[i];
mins.push({arr[0], i});
maxs.push({arr[arr.size() - 1], i});
}
int res = INT_MIN;
auto min_first = mins.top(); mins.pop();
auto max_first = maxs.top(); maxs.pop();
if (min_first.second != max_first.second) {
return max_first.first - min_first.first;
}
auto min_second = mins.top();
auto max_second = maxs.top();
return max(max_second.first - min_first.first, max_first.first - min_second.first);
}
};
``````

### # 保存已有的最大最小

C++代码如下：

``````class Solution {
public:
int maxDistance(vector<vector<int>>& arrays) {
const int N = arrays.size();
int curMin =  10010;
int curMax = -10010;
int res = 0;
for (auto& arr : arrays) {
res = max(res, (arr[arr.size() - 1] - curMin));
res = max(res, (curMax - arr[0]));
curMin = min(curMin, arr[0]);
curMax = max(curMax, arr[arr.size() - 1]);
}
return res;
}
};
``````

## # 日期

2019 年 9 月 19 日 —— 举杯邀明月，对影成三人