Maximum Distance in Arrays - Problem
Maximum Distance in Arrays - Find the greatest possible distance between elements from different sorted 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
Mountain Range Distance ProblemRange 1: [1,2,3]Min: 1Max: 3Range 2: [4,5]Min: 4Max: 5Range 3: [1,2,3]Min: 1Max: 3Maximum Distance: |1 - 5| = 4Key InsightSince arrays are sorted, only first and last elements matter!Find global min from one array and global max from another.
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.
Asked in
Google 45 Amazon 38 Meta 29 Apple 22
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen