#624

Maximum Distance in Arrays

Medium
ArrayGreedyArrayGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that the arrays are sorted. By only considering the minimum and maximum values of the first and last arrays, we can efficiently compute the maximum distance without needing to check every pair.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize `min_val` as the first element of the first array and `max_val` as the last element of the first array.
  2. 2Step 2: Loop through each subsequent array, updating `min_val` and `max_val` based on the first and last elements of the current array.
  3. 3Step 3: Calculate the maximum distance using the absolute differences between the current `min_val` and `max_val`.
solution.py11 lines
1# Full working Python code
2
3def maxDistance(arrays):
4    min_val = arrays[0][0]
5    max_val = arrays[0][-1]
6    max_distance = 0
7    for i in range(1, len(arrays)):
8        max_distance = max(max_distance, abs(arrays[i][-1] - min_val), abs(max_val - arrays[i][0]))
9        min_val = min(min_val, arrays[i][0])
10        max_val = max(max_val, arrays[i][-1])
11    return max_distance

Complexity note: This complexity is optimal because we only make a single pass through the arrays, updating our min and max values as we go.

  • 1The maximum distance can be achieved by comparing the smallest element of one array with the largest element of another.
  • 2Sorting of arrays allows us to efficiently access the minimum and maximum values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.