624. Maximum Distance in Arrays LeetCode Solution
In this guide, you will get 624. Maximum Distance in Arrays LeetCode Solution with the best time and space complexity. The solution to Maximum Distance in Arrays problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Distance in Arrays solution in C++
- Maximum Distance in Arrays solution in Java
- Maximum Distance in Arrays solution in Python
- Additional Resources
Problem Statement of Maximum Distance in Arrays
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.
Example 1:
Input: arrays = [[1,2,3],[4,5],[1,2,3]]
Output: 4
Explanation: 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.
Example 2:
Input: arrays = [[1],[1]]
Output: 0
Constraints:
m == arrays.length
2 <= m <= 105
1 <= arrays[i].length <= 500
-104 <= arrays[i][j] <= 104
arrays[i] is sorted in ascending order.
There will be at most 105 integers in all the arrays.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
624. Maximum Distance in Arrays LeetCode Solution in C++
class Solution {
public:
int mxDistance(vector<vector<int>>& arrays) {
int ans = 0;
int mn = 10000;
int mx = -10000;
for (const vector<int>& A : arrays) {
ans = max({ans, A.back() - mn, mx - A.front()});
mn = min(mn, A.front());
mx = max(mx, A.back());
}
return ans;
}
};
/* code provided by PROGIEZ */
624. Maximum Distance in Arrays LeetCode Solution in Java
class Solution {
public int maxDistance(List<List<Integer>> arrays) {
int ans = 0;
int mn = 10000;
int mx = -10000;
for (List<Integer> A : arrays) {
ans = Math.max(ans, Math.max(A.get(A.size() - 1) - mn, mx - A.get(0)));
mn = Math.min(mn, A.get(0));
mx = Math.max(mx, A.get(A.size() - 1));
}
return ans;
}
}
// code provided by PROGIEZ
624. Maximum Distance in Arrays LeetCode Solution in Python
class Solution:
def maxDistance(self, arrays: list[list[int]]) -> int:
ans = 0
mn = 10000
mx = -10000
for A in arrays:
ans = max(ans, A[-1] - mn, mx - A[0])
mn = min(mn, A[0])
mx = max(mx, A[-1])
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.