Maximum Distance in Arrays - Problem

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.

Input & Output

Example 1 — 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 — Different Arrays
$ Input: arrays = [[1],[1]]
Output: 0
💡 Note: Both arrays contain only 1, so the maximum distance is |1-1| = 0.
Example 3 — Negative Numbers
$ Input: arrays = [[-1,1],[-3,1,4],[-2,-1,0,2]]
Output: 6
💡 Note: Maximum distance is achieved by picking -2 from the third array and 4 from the second array, giving |4-(-2)| = 6.

Constraints

  • m == arrays.length
  • 2 ≤ m ≤ 105
  • 1 ≤ arrays[i].length ≤ 500
  • -104 ≤ arrays[i][j] ≤ 104
  • arrays[i] is sorted in ascending order.

Visualization

Tap to expand
Maximum Distance in Arrays INPUT m = 3 sorted arrays arr[0]: 1 2 3 arr[1]: 4 5 arr[2]: 1 2 3 Each Array: First elem = MIN Last elem = MAX min max Input: arrays = [[1,2,3], [4,5],[1,2,3]] Pick 2 nums from diff arrays ALGORITHM STEPS 1 Initialize Tracking globalMin=1, globalMax=3 (from arr[0]) 2 Process arr[1] curMin=4, curMax=5 dist1=|5-1|=4 dist2=|4-3|=1 maxDist=4 3 Update Global globalMin=min(1,4)=1 globalMax=max(3,5)=5 4 Process arr[2] curMin=1, curMax=3 dist1=|3-1|=2 dist2=|1-5|=4 maxDist stays 4 Min Max 1 3 1 5 1 5 FINAL RESULT Maximum Distance Found: 1 2 3 4 5 arr[0] arr[1] |5-1| = 4 Best Pair: a=1 from arr[0] b=5 from arr[1] OUTPUT 4 [OK] Verified Max distance = 4 Key Insight: Min-Max Optimization Since arrays are sorted, the minimum is always the first element and maximum is the last. For max distance across different arrays: track global min/max and compare with each array's endpoints. Time: O(n), Space: O(1). No need to compare all pairs - just track extremes! TutorialsPoint - Maximum Distance in Arrays | Min-Max Optimization Approach
Asked in
Google 15 Amazon 12 Apple 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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