Maximum Distance in Arrays - Problem
Maximum Distance in Arrays - Find the greatest possible distance between elements from different sorted arrays.
You are given
The distance between two integers
Goal: Return the maximum possible distance you can achieve.
Example: Given arrays
You are given
m arrays, where each array is sorted in ascending order. Your task is to pick exactly two integers from two different arrays (one element from each array) and calculate the distance between them.The distance between two integers
a and b is defined as their absolute difference |a - b|.Goal: Return the maximum possible distance you can achieve.
Example: Given arrays
[[1,2,3], [4,5], [1,2,3]], you could pick 1 from the first array and 5 from the second array for a distance of 4. Input & Output
example_1.py โ Basic Case
$
Input:
arrays = [[1,2,3],[4,5],[1,2,3]]
โบ
Output:
4
๐ก Note:
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.py โ Simple Case
$
Input:
arrays = [[1],[1]]
โบ
Output:
0
๐ก Note:
Since we can only pick from different arrays and both arrays contain the same element, the maximum distance is 0.
example_3.py โ Larger Range
$
Input:
arrays = [[1,4,5],[0,2]]
โบ
Output:
5
๐ก Note:
We can pick 0 from the second array and 5 from the first array to get the maximum distance of 5.
Constraints
- m == arrays.length
- 2 โค m โค 105
- 1 โค arrays[i].length โค 500
- -104 โค arrays[i][j] โค 104
- arrays[i] is sorted in ascending order
- There will be at most 5 ร 105 integers in all the arrays
Visualization
Tap to expand
Understanding the Visualization
1
Scout All Ranges
Identify the global lowest valley (minimum) and highest peak (maximum)
2
Calculate Distances
For each range, find the maximum distance using global extremes
3
Avoid Same Range
Ensure we pick peaks from different mountain ranges
Key Takeaway
๐ฏ Key Insight: The maximum distance must be between the smallest element of one array and the largest element of a different array, since all arrays are sorted in ascending order.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code