Maximum Distance in Arrays

题目

Givenmarrays, 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 integersaandbto 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.

Note:

  1. Each given array will have at least 1 number. There will be at least two non-empty arrays.
  2. The total number of the integers in all themarrays will be in the range of [2, 10000].
  3. The integers in themarrays will be in the range of [-10000, 10000].

思路分析

这道题看起来比较容易,但是很容易陷入一个误区,就是直接找到最大值跟最小值,然后相减。这个错误就是没有考虑到最大值跟最小值有可能在同一个subarray中,题目要求是从不同的subarray中取值。所以在找最大最小值的时候一定要记录所在的subarray的index,最后如果index不同,就直接最大值最小值相减,如果相同,还要求次小值和次大值。

class Solution(object):
    def maxDistance(self, arrays):
        """
        :type arrays: List[List[int]]
        :rtype: int
        """
        length = len(arrays)
        minVal = arrays[0][0]
        maxVal = arrays[0][-1]
        minIndex, maxIndex = 0, 0
        for i in range(1, len(arrays)):
            if arrays[i][0] < minVal: minVal, minIndex = arrays[i][0], i  <<< record the index of min 
        for i in range(1, len(arrays)):
            if arrays[i][-1] > maxVal: maxVal, maxIndex = arrays[i][-1], i   <<< record the index of max

        if minIndex != maxIndex: return maxVal-minVal

        secMax = max([arrays[i][-1] for i in range(len(arrays)) if i != maxIndex])
        secMin = min([arrays[i][0] for i in range(len(arrays)) if i != minIndex])
        return max(maxVal-secMin, secMax-minVal)

results matching ""

    No results matching ""