Formatted question description:

624. Maximum Distance in Arrays




Given m arrays, 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 integers a and b to be their absolute difference |a-b|. Your task is to find the maximum distance.

Example 1:

Output: 4
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.


  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 the m arrays will be in the range of [2, 10000].
  3. The integers in the m arrays will be in the range of [-10000, 10000].


For each array, obtain the minimum integer and the maximum integer in the array. Then loop over all arrays’ minimum integers and maximum integers, and find the maximum distance with the two elements from different arrays.

class Solution {
    public int maxDistance(List<List<Integer>> arrays) {
        int maxDistance = 0;
        int rows = arrays.size();
        int[][] minMaxArray = new int[rows][2];
        for (int i = 0; i < rows; i++) {
            List<Integer> row = arrays.get(i);
            int size = row.size();
            int curMin = row.get(0), curMax = row.get(size - 1);
            minMaxArray[i][0] = curMin;
            minMaxArray[i][1] = curMax;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < rows; j++) {
                if (i == j)
                maxDistance = Math.max(maxDistance, Math.max(Math.abs(minMaxArray[i][0] - minMaxArray[j][1]), Math.abs(minMaxArray[i][1] - minMaxArray[j][0])));
        return maxDistance;

All Problems

All Solutions