624. Maximum Distance in Arrays
Problem Description
You are given m
arrays where each array is sorted in ascending order. Your task is to pick two integers from two different arrays (one integer from each array) and calculate the distance between them. The distance between two integers a
and b
is defined as their absolute difference |a - b|
.
Your goal is to find and return the maximum distance possible.
For example, if you have arrays [1, 4, 5]
and [0, 2]
, you could pick:
5
from the first array and0
from the second array, giving distance|5 - 0| = 5
1
from the first array and2
from the second array, giving distance|1 - 2| = 1
- And other combinations...
The maximum distance would be 5
in this case.
The key constraint is that the two integers must come from different arrays - you cannot pick both integers from the same array.
Intuition
Since each array is sorted in ascending order, the smallest element is at the beginning and the largest element is at the end of each array. To maximize the distance |a - b|
, we want to pick two numbers that are as far apart as possible.
The key insight is that the maximum distance will always involve either:
- The minimum value from one array and the maximum value from another array
- The maximum value from one array and the minimum value from another array
Since arrays are sorted, we only need to consider the first element (minimum) and last element (maximum) of each array.
As we iterate through the arrays, we can keep track of the global minimum and maximum values seen so far. For each new array we encounter:
- We calculate the distance between the current array's minimum (first element) and the global maximum seen so far
- We calculate the distance between the current array's maximum (last element) and the global minimum seen so far
- We update our answer with the maximum of these distances
The reason we update the global minimum and maximum after calculating distances for the current array is crucial - this ensures we're always picking elements from different arrays. We're comparing the current array's elements with the min/max from previously seen arrays, guaranteeing they come from different sources.
This greedy approach works because we're always considering the most extreme values that could give us the maximum distance, and by processing arrays one by one, we naturally avoid picking two elements from the same array.
Learn more about Greedy patterns.
Solution Approach
We implement the solution by maintaining two variables throughout our traversal:
mi
: tracks the minimum value seen so far across all processed arraysmx
: tracks the maximum value seen so far across all processed arrays
Initialization:
We start by initializing mi
and mx
with the first and last elements of the first array respectively:
mi = arrays[0][0]
(first element of first array)mx = arrays[0][-1]
(last element of first array)ans = 0
(to store the maximum distance)
Main Loop:
We iterate through the remaining arrays starting from index 1. For each array arr
:
-
Calculate distances with current array:
a = abs(arr[0] - mx)
: Distance between current array's minimum and global maximumb = abs(arr[-1] - mi)
: Distance between current array's maximum and global minimum
-
Update maximum distance:
ans = max(ans, a, b)
: Keep track of the largest distance found so far
-
Update global min and max:
mi = min(mi, arr[0])
: Update global minimum if current array has a smaller first elementmx = max(mx, arr[-1])
: Update global maximum if current array has a larger last element
The order of operations is important here. We calculate distances using the current array's elements against the min/max from previously processed arrays before updating the global min/max. This ensures we never compare elements from the same array.
Time Complexity: O(m)
where m
is the number of arrays, since we visit each array exactly once.
Space Complexity: O(1)
as we only use a constant amount of extra space for variables mi
, mx
, and ans
.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with a concrete example to see how it works.
Given arrays: [[1, 4, 5], [0, 2], [3, 8, 9]]
Initialization:
- Start with the first array
[1, 4, 5]
mi = 1
(first element of first array)mx = 5
(last element of first array)ans = 0
Iteration 1: Process array [0, 2]
- Calculate distances:
a = |0 - 5| = 5
(current array's min vs global max)b = |2 - 1| = 1
(current array's max vs global min)
- Update answer:
ans = max(0, 5, 1) = 5
- Update global min/max:
mi = min(1, 0) = 0
mx = max(5, 2) = 5
Iteration 2: Process array [3, 8, 9]
- Calculate distances:
a = |3 - 5| = 2
(current array's min vs global max from arrays 0 and 1)b = |9 - 0| = 9
(current array's max vs global min from arrays 0 and 1)
- Update answer:
ans = max(5, 2, 9) = 9
- Update global min/max:
mi = min(0, 3) = 0
mx = max(5, 9) = 9
Result: The maximum distance is 9
, achieved by picking 9
from array [3, 8, 9]
and 0
from array [0, 2]
.
Notice how at each step, we compare the current array's extremes with the min/max values from previously processed arrays, ensuring we always pick elements from different arrays. The algorithm correctly identifies that the maximum distance comes from the largest value in the third array and the smallest value in the second array.
Solution Implementation
1class Solution:
2 def maxDistance(self, arrays: List[List[int]]) -> int:
3 """
4 Find the maximum distance between any two elements from different arrays.
5 Distance is defined as |a - b| where a and b are from different arrays.
6
7 Args:
8 arrays: List of sorted integer arrays
9
10 Returns:
11 Maximum distance between elements from different arrays
12 """
13 # Initialize the maximum distance
14 max_distance = 0
15
16 # Track the minimum and maximum values seen so far
17 # Start with the first array's minimum and maximum values
18 min_value = arrays[0][0]
19 max_value = arrays[0][-1]
20
21 # Iterate through remaining arrays
22 for current_array in arrays[1:]:
23 # Calculate distances between current array's extremes and previous extremes
24 # Distance from current array's minimum to previous maximum
25 distance_to_max = abs(current_array[0] - max_value)
26 # Distance from current array's maximum to previous minimum
27 distance_to_min = abs(current_array[-1] - min_value)
28
29 # Update the maximum distance found so far
30 max_distance = max(max_distance, distance_to_max, distance_to_min)
31
32 # Update global minimum and maximum for next iteration
33 min_value = min(min_value, current_array[0])
34 max_value = max(max_value, current_array[-1])
35
36 return max_distance
37
1class Solution {
2 public int maxDistance(List<List<Integer>> arrays) {
3 // Initialize the maximum distance
4 int maxDist = 0;
5
6 // Initialize min and max values from the first array
7 // Each array is sorted, so first element is min and last element is max
8 int minValue = arrays.get(0).get(0);
9 int maxValue = arrays.get(0).get(arrays.get(0).size() - 1);
10
11 // Iterate through remaining arrays starting from index 1
12 for (int i = 1; i < arrays.size(); ++i) {
13 List<Integer> currentArray = arrays.get(i);
14
15 // Calculate distances:
16 // Distance between current array's min and previous max
17 int distanceWithMax = Math.abs(currentArray.get(0) - maxValue);
18 // Distance between current array's max and previous min
19 int distanceWithMin = Math.abs(currentArray.get(currentArray.size() - 1) - minValue);
20
21 // Update maximum distance
22 maxDist = Math.max(maxDist, Math.max(distanceWithMax, distanceWithMin));
23
24 // Update global min and max values for next iteration
25 minValue = Math.min(minValue, currentArray.get(0));
26 maxValue = Math.max(maxValue, currentArray.get(currentArray.size() - 1));
27 }
28
29 return maxDist;
30 }
31}
32
1class Solution {
2public:
3 int maxDistance(vector<vector<int>>& arrays) {
4 // Initialize the maximum distance result
5 int maxDist = 0;
6
7 // Initialize min and max values from the first array
8 // Each array is sorted, so first element is min, last element is max
9 int globalMin = arrays[0][0];
10 int globalMax = arrays[0][arrays[0].size() - 1];
11
12 // Iterate through remaining arrays starting from index 1
13 for (int i = 1; i < arrays.size(); ++i) {
14 // Get reference to current array for efficiency
15 const auto& currentArray = arrays[i];
16
17 // Calculate distances:
18 // - Distance between current array's min and global max
19 int distToGlobalMax = abs(currentArray[0] - globalMax);
20 // - Distance between current array's max and global min
21 int distToGlobalMin = abs(currentArray[currentArray.size() - 1] - globalMin);
22
23 // Update maximum distance found so far
24 maxDist = max({maxDist, distToGlobalMax, distToGlobalMin});
25
26 // Update global min and max values for next iteration
27 globalMin = min(globalMin, currentArray[0]);
28 globalMax = max(globalMax, currentArray[currentArray.size() - 1]);
29 }
30
31 return maxDist;
32 }
33};
34
1/**
2 * Finds the maximum distance between any two elements from different arrays
3 * @param arrays - A list of sorted arrays (each array is sorted in ascending order)
4 * @returns The maximum distance between elements from different arrays
5 */
6function maxDistance(arrays: number[][]): number {
7 // Initialize the maximum distance result
8 let maxDistanceResult: number = 0;
9
10 // Track the minimum value from all arrays seen so far
11 let minValue: number = arrays[0][0];
12 // Track the maximum value from all arrays seen so far
13 let maxValue: number = arrays[0][arrays[0].length - 1];
14
15 // Iterate through remaining arrays starting from index 1
16 for (let i = 1; i < arrays.length; i++) {
17 const currentArray: number[] = arrays[i];
18
19 // Calculate distance between current array's minimum and previous maximum
20 const distanceToMax: number = Math.abs(currentArray[0] - maxValue);
21
22 // Calculate distance between current array's maximum and previous minimum
23 const distanceToMin: number = Math.abs(currentArray[currentArray.length - 1] - minValue);
24
25 // Update maximum distance if a larger distance is found
26 maxDistanceResult = Math.max(maxDistanceResult, distanceToMax, distanceToMin);
27
28 // Update global minimum value
29 minValue = Math.min(minValue, currentArray[0]);
30
31 // Update global maximum value
32 maxValue = Math.max(maxValue, currentArray[currentArray.length - 1]);
33 }
34
35 return maxDistanceResult;
36}
37
Time and Space Complexity
The time complexity is O(m)
, where m
is the number of arrays. The algorithm iterates through the list of arrays exactly once (from index 1 to the end), performing constant-time operations for each array: accessing the first and last elements, computing absolute differences, updating the minimum and maximum values, and comparing values. Since each operation within the loop takes O(1)
time and the loop runs m-1
times, the overall time complexity is O(m)
.
The space complexity is O(1)
. The algorithm only uses a fixed amount of extra space regardless of the input size. It maintains four variables: ans
for storing the maximum distance, mi
for the minimum value seen so far, mx
for the maximum value seen so far, and temporary variables a
and b
for intermediate calculations. These variables do not scale with the number of arrays, resulting in constant space usage.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
Pitfall: Comparing Elements from the Same Array
The most common mistake is accidentally comparing elements from the same array when calculating the maximum distance. This violates the problem's constraint that the two integers must come from different arrays.
Incorrect Approach:
def maxDistance(arrays):
# WRONG: Collecting all values first
all_mins = [arr[0] for arr in arrays]
all_maxs = [arr[-1] for arr in arrays]
# This might pick min and max from the same array!
return max(all_maxs) - min(all_mins)
Why it fails:
Consider arrays = [[1, 5], [3, 4]]
- The incorrect approach would calculate:
max(5, 4) - min(1, 3) = 5 - 1 = 4
- But both 5 and 1 come from the first array
[1, 5]
, which is invalid - The correct answer is
3
(either|5 - 3| = 2
or|1 - 4| = 3
)
Pitfall: Updating Min/Max Before Calculating Distances
Another subtle error is updating the global minimum and maximum values before using them to calculate distances with the current array.
Incorrect Order:
def maxDistance(arrays):
mi = arrays[0][0]
mx = arrays[0][-1]
ans = 0
for arr in arrays[1:]:
# WRONG: Updating before calculating distances
mi = min(mi, arr[0])
mx = max(mx, arr[-1])
# Now we might be comparing arr's own elements!
ans = max(ans, abs(arr[0] - mx), abs(arr[-1] - mi))
return ans
Solution:
The correct approach maintains the invariant that when processing array i
, the mi
and mx
values only contain information from arrays 0
through i-1
. This ensures we never compare elements from the same array:
def maxDistance(arrays):
mi = arrays[0][0]
mx = arrays[0][-1]
ans = 0
for arr in arrays[1:]:
# CORRECT: Calculate distances first
ans = max(ans, abs(arr[0] - mx), abs(arr[-1] - mi))
# Then update for next iteration
mi = min(mi, arr[0])
mx = max(mx, arr[-1])
return ans
The key insight is that the order of operations matters: always calculate distances before updating the global tracking variables.
What are the most two important steps in writing a depth first search function? (Select 2)
Recommended Readings
Greedy Introduction div class responsive iframe iframe src https www youtube com embed WTslqPbj7I title YouTube video player frameborder 0 allow accelerometer autoplay clipboard write encrypted media gyroscope picture in picture web share allowfullscreen iframe div When do we use greedy Greedy algorithms tend to solve optimization problems Typically they will ask you to calculate the max min of some value Commonly you may see this phrased in the problem as max min longest shortest largest smallest etc These keywords can be identified by just scanning
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Donβt Miss This!