1 minute read

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 abs(a-b).

URL: https://leetcode.com/problems/maximum-distance-in-arrays/

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int maxDistance(List<List<Integer>> arrays) {
        if (arrays.size() == 1) {
            return 0;
        }
		//1.store the min value and max value using the first array
        int min_val = arrays.get(0).get(0);
        int max_val = arrays.get(0).get(arrays.get(0).size()-1);
        
        int max_dist = Integer.MIN_VALUE;
        for (int i = 1; i < arrays.size(); i++) {
            //2. calculate and store the max difference for the new array
            max_dist = Math.max(max_dist,max_val - arrays.get(i).get(0));
            max_dist = Math.max(max_dist, arrays.get(i).get(arrays.get(i).size()-1)- min_val);
            //3.Update max value and min value
            min_val = Math.min(min_val,arrays.get(i).get(0));
            max_val = Math.max(max_val,arrays.get(i).get(arrays.get(i).size()-1));
        }
        return max_dist;
    }
}

Explanation:
Line 3 checks if the array only has one element, in this case just return 0.

Lines 7 and 8 store the minimum value and maximum value using the first array.

Line 11 loops through the rest of the arrays.

Lines 13 and 14 stores the greater of the following values into max_dist: current max_dist, max_val - minimum value of current array, maximum value of current array - min_val

Lines 16 and 17 store the maximum and minimum value seen so far by examining the current array.

Upon termination of the loop, the maximum distance will have been calculated.

Line 19 returns this maximum distance.