624. Maximum Distance in Arrays

Maximum Distance in Arrays - LeetCode 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

  • code
class Solution:
    def maxDistance(self, arrays: List[List[int]]) -> int:
        curmin, curmax = arrays[0][0], arrays[0][-1]
        res = 0
        for i in range(1, len(arrays)):
            curres = max(abs(curmax - arrays[i][0]), abs(curmin - arrays[i][-1]))
            res = max(curres, res)
            curmin = min(curmin, arrays[i][0])
            curmax = max(curmax, arrays[i][-1])
            
        return res
  • code
class Solution {
    public int maxDistance(List<List<Integer>> arrays) {
        List<Integer> first = arrays.get(0);
        int min = first.get(0);
        int max = first.get(first.size()-1);
        int res = 0;
        
        for (int i = 1; i < arrays.size(); i++) {
            List<Integer> cur = arrays.get(i);
            int curmin = cur.get(0);
            int curmax = cur.get(cur.size()-1);            
            
            res = Math.max(res, Math.max(Math.abs(curmin - max), Math.abs(curmax - min)));
            min = Math.min(min, curmin);
            max = Math.max(max, curmax);
            
        }
        
        return res;
    }
}