# LeetCode Maximum Distance in Arrays

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

```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].

```class Solution {
struct P {
int idx;
int value;
P(int i, int v) :idx(i), value(v) {};
bool operator<(const P& p) {
return this->value < p.value;
}
};
public:
int maxDistance(vector<vector<int>>& arrays) {
vector<P> vp;
for (int i = 0; i < arrays.size(); ++i) {
vp.push_back({ i,arrays[i][0] });
vp.push_back({ i,arrays[i][arrays[i].size() - 1] });
}
sort(vp.begin(), vp.end());
int ans = 0, n = vp.size();
if (vp[0].idx != vp[n - 1].idx)return abs(vp[n - 1].value - vp[0].value);
return max(abs(vp[n - 1].value - vp[1].value), abs(vp[n - 2].value - vp[0].value));
}
};
```

```class Solution {
public:
int maxDistance(vector<vector<int>>& arrays) {
int ans = INT_MIN;
int curMin = arrays[0][0], curMax = arrays[0][arrays[0].size() - 1];
for(int i = 1; i < arrays.size(); ++i) {
ans = max(ans, abs(arrays[i][0] - curMax));
ans = max(ans, abs(arrays[i][arrays[i].size() - 1] - curMin));
curMin = min(curMin, arrays[i][0]);
curMax = max(curMax, arrays[i][arrays[i].size() - 1]);
}
return ans;
}
};
```