Problem
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 |a - b|
.
Return the maximum distance.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Solution
This solution can be solved by using greedy paradigm. Please find the video explanation below:
Method 1 - Min and Max Difference
Here are the steps we can take:
- Understand the formula:
- The distance between two integers (a) and (b) from two different arrays is (|a - b|).
- Leverage Sorted Property:
- Since each array is sorted in ascending order, the smallest number from an array is the first element, and the largest number is the last element.
- Track Min and Max Values across Arrays:
- As we iterate through each array, we keep track of the global minimum value and the global maximum value so far.
- We also compute and update the maximum distance by comparing the first element of the current array with the global maximum value encountered so far and the last element of the current array with the global minimum value encountered so far.
- Update the global minimum and global maximum values accordingly.
Code
|
|
Complexity
- ⏰ Time complexity:
O(m)
wherem
is number of arrays, as we pass through each array exactly once, that too checking only min and max values. - 🧺 Space complexity:
O(1)
Method 2 - Calculating Global and Second maxima and minima
We can use a slightly different approach by finding the global minimum and maximum values among different arrays and handle the cases when the minimum and maximum values come from the same array by comparing with the second minimum and second maximum values from other arrays. Here’s the detailed approach:
Approach:
- Identify Global Min and Max:
- First, find the overall minimum and maximum values and their respective array indices.
- Handle Same Array Case:
- If the global minimum and maximum are from the same array, find the second minimum and second maximum by ignoring elements from this array.
- Compute distances between the pairs of values (min and second max, max and second min).
- Return the Largest Distance:
- The answer will be the maximum of these computed distances.
Code
|
|
Complexity
- ⏰ Time complexity:
O(m)
- 🧺 Space complexity:
O(1)