# Python 7 lines: min and max twice

• Find the min and max of all elements as `min1` and `max1`

• If `min1` and `max1` belong to different arrays, then we are done.

• If `min1` and `max1` lie in the same array, we need to find the second min and max in the elements donated by `min2` and `max2`.

• The result should be `max2-min1` or `max1-min2`. Pick the larger one.

``````class Solution(object):
def maxDistance(self, arrays):
"""
:type arrays: List[List[int]]
:rtype: int
"""
# find the 1st min and 1st max along with their associated array indices in arrays
min1, imin1 = min((array[0], i) for i, array in enumerate(arrays))
max1, imax1 = max((array[-1], i) for i, array in enumerate(arrays))
if imin1 != imax1:
return max1 - min1
# find the 2nd min and 2nd max
min2 = min(array[0] for i, array in enumerate(arrays) if i != imin1)
max2 = max(array[-1] for i, array in enumerate(arrays) if i != imax1)
return max(max2 - min1, max1 - min2)``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.