Maximum Distance in Arrays Problem
Description
LeetCode Problem 624.
You are given m arrays, where each array is sorted in ascending order.
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|.
Return the maximum distance.
Example 1:
Input: arrays = [[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.
Example 2:
Input: arrays = [[1],[1]]
Output: 0
Constraints:
m == arrays.length2 <= m <= 10^51 <= arrays[i].length <= 500-10^4 <= arrays[i][j] <= 10^4arrays[i]is sorted in ascending order.- There will be at most
10^5integers in all the arrays.
Solution
Approach: Running Minimum and Maximum
Every array is sorted, so the only values worth picking from an array are its two ends: its first element (its minimum) and its last element (its maximum). The largest distance is always some array's maximum minus a different array's minimum.
The catch is the word different. Simply taking the global maximum minus the global minimum fails when both come from the same array: in [[1,100],[50,60]] that would give 99, but the real answer is 59 (60 - 1).
To respect the rule, scan the arrays in order and keep lo and hi, the smallest first element and the largest last element among the arrays seen so far. For each new array with ends a and b:
- compare it with the earlier arrays first: the candidates are
hi - aandb - lo; - only then merge it in:
lo = min(lo, a),hi = max(hi, b).
Because the current array is compared before it joins lo and hi, its own two ends are never paired with each other. And every pair of different arrays is still considered, from the side of whichever of the two comes later.
Complexity: O(m) time for m arrays (we only look at their ends) and O(1) extra space.
class Solution:
def maxDistance(self, arrays: List[List[int]]) -> int:
ans = 0
# Smallest and largest value among the arrays before the current one.
lo, hi = arrays[0][0], arrays[0][-1]
for arr in arrays[1:]:
# Pair this array's ends with the other arrays' extremes, then let it join them.
ans = max(ans, hi - arr[0], arr[-1] - lo)
lo = min(lo, arr[0])
hi = max(hi, arr[-1])
return ans