Maximum Distance in Arrays

You are given m arrays, where 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 integers a and b to be their absolute difference |a - b|. Your task is to find 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

Example 3:

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

Example 4:

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

 

Constraints:


Solution:

class Solution {
    public int maxDistance(List<List<Integer>> arrays) {
        int result = Integer.MIN_VALUE;
        int max = arrays.get(0).get(arrays.get(0).size() - 1);
        int min = arrays.get(0).get(0);
        
        for (int i = 1; i < arrays.size(); i ++) {
            List<Integer> curr = arrays.get(i);
            result = Math.max(result, Math.abs(curr.get(curr.size() - 1) - min));
            result = Math.max(result, Math.abs(max - curr.get(0)));
            min = Math.min(min, curr.get(0));
            max = Math.max(max, curr.get(curr.size() - 1));
        }
        return result;
    }
}