Formatted question description: https://leetcode.ca/all/624.html

# 624. Maximum Distance in Arrays

Easy

## Description

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

## Solution

For each array, obtain the minimum integer and the maximum integer in the array. Then loop over all arrays’ minimum integers and maximum integers, and find the maximum distance with the two elements from different arrays.

• class Solution {
public int maxDistance(List<List<Integer>> arrays) {
int maxDistance = 0;
int rows = arrays.size();
int[][] minMaxArray = new int[rows];
for (int i = 0; i < rows; i++) {
List<Integer> row = arrays.get(i);
int size = row.size();
int curMin = row.get(0), curMax = row.get(size - 1);
minMaxArray[i] = curMin;
minMaxArray[i] = curMax;
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
if (i == j)
continue;
maxDistance = Math.max(maxDistance, Math.max(Math.abs(minMaxArray[i] - minMaxArray[j]), Math.abs(minMaxArray[i] - minMaxArray[j])));
}
}
return maxDistance;
}
}

• // OJ: https://leetcode.com/problems/maximum-distance-in-arrays/
// Time: O(N)
// Space: O(1)
class Solution {
public:
int maxDistance(vector<vector<int>>& A) {
int mn = 1e5, mx = -1e5, ans = 0;
for (auto &v : A) {
ans = max({ ans, mx - v, v.back() - mn });
mx = max(mx, v.back());
mn = min(mn, v);
}
return ans;
}
};

• class Solution(object):
# subarray sum
def _maxDistance(self, arrays):
"""
:type arrays: List[List[int]]
:rtype: int
"""
n = len(arrays)
minArray, maxArray = [], []
for i in range(n):
minArray.append(arrays[i])
maxArray.append(arrays[i][-1])
lMax = [maxArray] * n
rMax = [maxArray[-1]] * n
ans = float("-inf")
for i in range(1, n):
lMax[i] = max(lMax[i - 1], maxArray[i])
for i in reversed(range(0, n - 1)):
rMax[i] = max(rMax[i + 1], maxArray[i])
for i in range(n):
if 0 < i < n - 1:
ans = max(ans, abs(max(lMax[i - 1], rMax[i + 1]) - minArray[i]))
elif i == 0:
ans = max(ans, abs(rMax[i + 1] - minArray[i]))
else:
ans = max(ans, abs(lMax[i - 1] - minArray[i]))
return ans

# one pass
def maxDistance(self, arrays):
n = len(arrays)
minNum = arrays
maxNum = arrays[-1]
ans = float("-inf")
for i in range(1, n):