# Maximum Distance in Arrays

Given`m`arrays, and each array is sorted in ascending order. Now 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|`. Your task is to find the maximum distance.

**Example 1:**

```
Input:

[[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.
```

注意：两个值不能从同一个array里取出,所以先比较结果，后更新start和wend，否则可能出现start和end在同一个array取出的情况

用两个变量start和end分别表示当前遍历过的数组中最小的首元素，和最大的尾元素，那么每当我们遍历到一个新的数组时，只需计算新数组尾元素和start绝对差，跟end和新数组首元素的绝对差，取二者之间的较大值来更新结果res即可，参见代码如下：

```
class Solution(object):
    def maxDistance(self, arrays):
        """
        :type arrays: List[List[int]]
        :rtype: int
        """

        res = 0
        start, end = arrays[0][0], arrays[0][-1]
        for row in arrays[1:]:
            res = max(res, abs(row[-1] - start))
            res = max(res, abs(end - row[0]))
            start = min(start, row[0])
            end = max(end, row[-1])
        return res
```

```
class Solution(object):
    def maxDistance(self, arrays):
        """
        :type arrays: List[List[int]]
        :rtype: int
        """
        m = len(arrays)
        MAX, max_i = max([(arrays[i][-1], i) for i in range(m)])
        MIN, min_i = min([(arrays[i][0], i) for i in range(m)])
        a = max(abs(arrays[i][0] - MAX) for i in range(m) if i != max_i)
        b = max(abs(arrays[i][-1] - MIN) for i in range(m) if i != min_i)
        return max(a, b)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://rachel2011.gitbook.io/leetcode_cc150/leetcode/maximum-distance-in-arrays.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
