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.

https://leetcode.cn/problems/maximum-distance-in-arrays/

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.length
  • 2 <= m <= 10⁵
  • 1 <= arrays[i].length <= 500
  • -10⁴ <= arrays[i][j] <= 10⁴
  • arrays[i] is sorted in ascending order.
  • There will be at most 10⁵ integers in all the arrays.

Test Cases

1
2
class Solution:
def maxDistance(self, arrays: List[List[int]]) -> int:
solution_test.py
1
2
3
4
5
6
7
8
9
10
11
12
import pytest

from solution import Solution


@pytest.mark.parametrize('arrays, expected', [
([[1,2,3],[4,5],[1,2,3]], 4),
([[1],[1]], 0),
])
@pytest.mark.parametrize('sol', [Solution()])
def test_solution(sol, arrays, expected):
assert sol.maxDistance(arrays) == expected

Thoughts

先取所有数组最大值(最后一个数字)的最大值记为 mx,所有数组最小值(第一个数字)的最小值记为 mn。

如果 mx 和 mn 来自不同的数组,那么结果为 mx - mn

否则需要取所有数组最大值的第二大记为 mx2,所有数组最小值的第二小记为 mn2,那么结果为 max{mx - mn2, mx2 - mn}

时间复杂度 O(m),空间复杂度 O(1)

Code

solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
max2 = lambda a, b: a if a >= b else b

class Solution:
def maxDistance(self, arrays: list[list[int]]) -> int:
if arrays[0][-1] >= arrays[1][-1]:
mxi, mx, mx2 = 0, arrays[0][-1], arrays[1][-1]
else:
mxi, mx, mx2 = 1, arrays[1][-1], arrays[0][-1]

if arrays[0][0] <= arrays[1][0]:
mni, mn, mn2 = 0, arrays[0][0], arrays[1][0]
else:
mni, mn, mn2 = 1, arrays[1][0], arrays[0][0]

for i in range(2, len(arrays)):
if arrays[i][-1] >= mx:
mxi, mx, mx2 = i, arrays[i][-1], mx
elif arrays[i][-1] >= mx2:
mx2 = arrays[i][-1]

if arrays[i][0] <= mn:
mni, mn, mn2 = i, arrays[i][0], mn
elif arrays[i][0] <= mn2:
mn2 = arrays[i][0]

if mxi != mni:
return mx - mn
else:
return max2(mx - mn2, mx2 - mn)