LeetCode 0624. Maximum Distance in Arrays Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0624. Maximum Distance in Arrays

Description

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.

Solutions

Solution 1: Maintain Maximum and Minimum Values

We notice that the maximum distance must be the distance between the maximum value in one array and the minimum value in another array. Therefore, we can maintain two variables mi and mx, representing the minimum and maximum values of the arrays we have traversed. Initially, mi and mx are the first and last elements of the first array, respectively.

Next, we traverse from the second array. For each array, we first calculate the distance between the first element of the current array and mx, and the distance between the last element of the current array and mi. Then, we update the maximum distance. At the same time, we update mi = min(mi, arr[0]) and mx = max(mx, arr[size - 1]).

After traversing all arrays, we get the maximum distance.

The time complexity is O(m), where m is the number of arrays. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def maxDistance(self, arrays: List[List[int]]) -> int: ans = 0 mi, mx = arrays[0][0], arrays[0][-1] for arr in arrays[1:]: a, b = abs(arr[0] - mx), abs(arr[-1] - mi) ans = max(ans, a, b) mi = min(mi, arr[0]) mx = max(mx, arr[-1]) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !