624. Maximum Distance in Arrays

Medium (Trung bình) Python 🔗 Xem trên LeetCode

📋 Đề Bài

You are given m arrays, where each array is sorted in ascending order.

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

Return the maximum distance.

 

Example 1:

Input: arrays = [[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.

Example 2:

Input: arrays = [[1],[1]]
Output: 0

 

Constraints:

  • m == arrays.length
  • 2 <= m <= 105
  • 1 <= arrays[i].length <= 500
  • -104 <= arrays[i][j] <= 104
  • arrays[i] is sorted in ascending order.
  • There will be at most 105 integers in all the arrays.

💻 Lời Giải

Python 0624-maximum-distance-in-arrays.py
class Solution:
    def maxDistance(self, a: List[List[int]]) -> int:
        n = len(a)
        
        prev_max = []
        prev_min = []
        suff_max = []
        suff_min = []
        
        for i in range(n):
            if i == 0:
                prev_max.append(a[i][-1])
                prev_min.append(a[i][-0])
            else:
                prev_max.append(max(prev_max[-1], a[i][-1]))
                prev_min.append(min(prev_min[-1], a[i][-0]))
                
        for i in range(n - 1, -1, -1):
            if i == n - 1:
                suff_max.append(a[i][-1])
                suff_min.append(a[i][-0])
            else:
                suff_max.append(max(suff_max[-1], a[i][-1]))
                suff_min.append(min(suff_min[-1], a[i][-0]))
                
        suff_min = suff_min[::-1]
        suff_max = suff_max[::-1]
        
        ans = 0
        
        for i in range(n):
            if i - 1 >= 0:
                ans = max(ans, prev_max[i - 1] - a[i][-0])
                ans = max(ans, a[i][-1] - prev_min[i - 1])
                
            if i + 1 < n:
                ans = max(ans, suff_max[i + 1] - a[i][-0])
                ans = max(ans, a[i][-1] - suff_min[i + 1])
                
        return ans