Maximum Distance in Arrays

Medium

Description

You are given m arrays, where each array is sorted in ascending order. You can pick up two integers from two different arrays and calculate the distance as |a - b|. Return the maximum distance.

Examples

Input:arrays = [[1,2,3],[4,5],[1,2,3]]
Output:4
Explanation:

Max distance: |5 - 1| = 4.

Input:arrays = [[1]]
Output:1
Explanation:

Minimal case with a single array containing one element.

Input:arrays = [[1,4,5],[2,3]]
Output:4
Explanation:

The maximum distance comes from taking the minimum of one array and the maximum of another: min([2,3])=2 and max([1,4,5])=5, giving |5-2|=3. Alternatively, max([2,3])=3 and min([1,4,5])=1 gives |3-1|=2. The maximum distance is 4.

Constraints

  • m == arrays.length
  • 2 ≤ m ≤ 10^5
  • 1 ≤ arrays[i].length ≤ 500

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!