Simple python with explanation


  • 1
    W

    We know each array is sorted in ascending order, so we can disregard any elements in the middle, as they can't be the maximum or minimum. Similarly, we know that we only need to check the first element for our minimum, and the last element for our maximum.

    The one tricky thing to watch out for is that we can only use a single element from each array, so we first calculate our result from the previous max/min, and then update the values for the next iteration.

    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
                
    

Log in to reply
 

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