56ms, beats 100% python solutions


  • 0
    K

    Idea is simple, first find the top 2 minum and maximum values, keep their inedexes, if the number 1 min and number 1 max values are not form same array, we can just return max1 - min1. Otherwise the result must be max2 - min1 or max1 - min2.

    class Solution(object):
        def maxDistance(self, arrays):
            """
            :type arrays: List[List[int]]
            :rtype: int
            """
            min1, min2, max1, max2 = float('inf'), float('inf'), -float('inf'), -float('inf')
            min1Idx, min2Idx, max1Idx, max2Idx = -1, -1, -1, -1
            for idx, arr in enumerate(arrays):
                if arr[0] < min1:
                    min2 = min1
                    min2Idx = min1Idx
                    min1 = arr[0]
                    min1Idx = idx
                elif arr[0] < min2:
                    min2 = arr[0]
                    min2Idx = idx
                    
                if arr[-1] > max1:
                    max2 = max1
                    max2Idx = max1Idx
                    max1 = arr[-1]
                    max1Idx = idx
                elif arr[-1] > max2:
                    max2 = arr[-1]
                    max2Idx = id
                
            if min1Idx != max1Idx:
                return max1 - min1
                
            return max(max2 - min1, max1 - min2)
    

Log in to reply
 

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