Leetcode 624. Maximum Distance in Arrays

Problem explanation

Given m arrays, where each array is already sorted in ascending order, we want to pick two integers, each integer from a different array and calculate the "distance". The "distance" is defined as the absolute difference between the two integers. The task is to find the maximum possible distance.

The solution code iterates over all the arrays, and at each iteration it calculates the new maximum distance using the current array's maximum and overall minimum, as well as the current array's minimum and overall maximum. For each new array, we update our overall minimum and maximum.

Here is a sample run using your example:

Initially, min and max are set to 10000 and -10000 respectively.

We then start iterating over the arrays:

In the first iteration, min is updated to 1, max is updated to 3 and the maximum distance seen so far is 0.

In the second iteration, the potential new maximum distances are 5-1=4 and 3-4=-1, so the maximum distance is updated to 4. Also, min and max remain the same.

In the third iteration, the potential new maximum distances are 3-1=2 and 3-1=2 which are both smaller than the current maximum distance (4), so we don't update it. However, min is updated to 1.

At the end, the maximum distance is 4.

Solution

C++

1
2c++
3class Solution {
4public:
5    int maxDistance(vector<vector<int>>& arrays) {
6        int ans = 0;
7        int min = arrays[0][0];
8        int max = arrays[0].back();
9
10        for (int i=1; i< arrays.size();++i) {
11            ans = max({ans, abs(arrays[i][0] - max),abs(arrays[i].back() - min)});
12            
13            min = min(min, arrays[i][0]);
14            max = max(max, arrays[i].back());
15        }
16        return ans;
17    }
18};```
19
20
21
22## Python
23

python class Solution: def maxDistance(self, arrays: List[List[int]]) -> int: min_val = arrays[0][0] max_val = arrays[0][-1]

1    max_diff = 0
2
3    for arr in arrays[1:]:
4        max_diff = max(max_diff, abs(max_val - arr[0]), abs(arr[-1] - min_val))
5        min_val = min(min_val, arr[0])
6        max_val = max(max_val, arr[-1])
7
8    return max_diff
1
2
3
4## Java
5

java public class Solution { public int maxDistance(List<List> arrays) { int result = 0; int min_val = arrays.get(0).get(0); int max_val = arrays.get(0).get(arrays.get(0).size()-1);

1    for(int i=1; i<arrays.size(); ++i){
2        result = Math.max(result, Math.max(Math.abs(max_val - arrays.get(i).get(0)),Math.abs(arrays.get(i).get(arrays.get(i).size()-1) - min_val)));
3        min_val = Math.min(min_val, arrays.get(i).get(0));
4        max_val = Math.max(max_val, arrays.get(i).get(arrays.get(i).size()-1));
5    }
6    return result;
7}

}```

JavaScript

1
2javascript
3class Solution {
4    maxDistance(arrays) {
5        let maxDiff = 0;
6        let minVal = arrays[0][0];
7        let maxVal = arrays[0][arrays[0].length - 1];
8
9        for (let i = 1; i < arrays.length; i++) {
10            maxDiff = Math.max(maxDiff,
11                               Math.abs(arrays[i][0] - maxVal),
12                               Math.abs(arrays[i][arrays[i].length - 1] - minVal)
13                               );
14            minVal = Math.min(minVal, arrays[i][0]);
15            maxVal = Math.max(maxVal, arrays[i][arrays[i].length - 1]);
16        }
17
18        return maxDiff;
19    }
20}```
21
22
23
24## C#
25

c# public class Solution { public int MaxDistance(IList<IList> arrays) { int result = 0; int min = arrays[0][0]; int max = arrays[0][arrays[0].Count - 1];

1    for(int i = 1; i < arrays.Count; ++i) {
2        result = Math.Max(result, Math.Max(Math.Abs(max - arrays[i][0]), Math.Abs(arrays[i][arrays[i].Count - 1] - min)));
3        
4        min = Math.Min(min, arrays[i][0]);
5        max = Math.Max(max, arrays[i][arrays[i].Count - 1]);
6    }
7
8    return result;
9}

}

1
2# Analysis
3
4The above solution iterates over the arrays and at each step calculates the new maximum distance based on the current array's max and min values along with the overall max and min values seen till then. If the new maximum distance is bigger than the current maximum, it updates the current maximum. It also updates the overall min and max values if needed. This solution takes linear time proportional to the length of the inputs (i.e., number of arrays) and thus is very efficient.
5
6As for the space complexity, it uses only a constant amount of space to store the overall min and max, and the max distance seen so far. Therefore, the space complexity is constant time, O(1).
7
8While the solution provided here is efficient in terms of time and space complexity, it's helpful to note that this problem does not have a unique solution. An alternative approach could be sorting or using priority queues. However, given the sorted nature of the input arrays, the solution provided here is an effective and efficient way to solve this problem. These solutions work by leveraging the fact that the arrays are already ordered, which means we can make some valid assumptions about the structure of the data we're dealing with.
9
10For example, in Python, we can always assume that the first element of the list will be the smallest (min) and the last element the largest (max). This allows us to quickly calculate the potential maximum distance at each step and update our records accordingly as we loop through the chosen integers. The same principles apply to the other languages in these examples. This leads to fast, and memory-efficient code.
11
12In conclusion, by understanding and exploiting the properties of the input arrays being sorted, we can develop an efficient algorithm to solve the problem which works in O(n) time and O(1) space, where n is the number of input arrays, a significant performance gain over other potential solutions.

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫