Maximum Distance in Arrays (LeetCode 624): Solution and Explanation

Medium
Array
Greedy

Given several sorted arrays, pick one number from each of two different arrays so that their difference is as large as possible, and return that difference.

Intuition

Each array is sorted, so its smallest value is its first element and its largest is its last. Anything in the middle can never beat the ends.

The obvious answer, global max minus global min, breaks when both come from the same array. That is the whole difficulty of the problem.

Scan the arrays in order. For the current array, the best partner among earlier arrays is either the smallest first value so far or the largest last value so far.

Compare first, update the running extremes second. That ordering guarantees the two numbers always come from different arrays.

Approach: One pass with running min and max

  1. Set lo = arrays[0][0], hi = arrays[0][-1] and best = 0.
  2. For every later array with ends first and last, set best = max(best, last - lo, hi - first).
  3. Then set lo = min(lo, first) and hi = max(hi, last).
  4. Return best.

Step-by-step example

arrays = [[1,2,3],[4,5],[1,2,3]]
  1. Array 0 seeds lo = 1 and hi = 3, best = 0.
  2. Array 1 has ends 4 and 5: 5 - 1 = 4 and 3 - 4 = -1, so best = 4. Then hi becomes 5.
  3. Array 2 has ends 1 and 3: 3 - 1 = 2 and 5 - 1 = 4, so best stays 4.
  4. The answer is 4.

Code: Python, Java, C++

1class Solution:
2    def maxDistance(self, arrays: List[List[int]]) -> int:
3        lo, hi = arrays[0][0], arrays[0][-1]
4        best = 0
5        for arr in arrays[1:]:
6            best = max(best, arr[-1] - lo, hi - arr[0])
7            lo = min(lo, arr[0])
8            hi = max(hi, arr[-1])
9        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m)

Each array is visited once and only its two ends are read.

Space

O(1)

Only lo, hi and best are stored.

Other approaches

Track the two smallest and two largest ends (time O(m), space O(1))

Record the smallest and second smallest first values and the largest and second largest last values with their array indices. If the global min and max come from different arrays, subtract them; otherwise try the two mixed combinations.

Brute force over array pairs (time O(m^2), space O(1))

For every pair of arrays, compare the first of one with the last of the other. Correct but too slow for 10^5 arrays.

Common mistakes

  • Returning global max minus global min. Both can belong to the same array, as in [[1, 9], [2, 3]].
  • Updating lo and hi before comparing. Then the current array can pair with itself.
  • Scanning every element of each array. Only the ends matter since each array is sorted.
  • Starting best at the first array's span. A single array cannot provide both numbers.

Frequently asked questions

Why is it enough to compare against the running lo and hi?

For any pair of arrays i < j, the pair is checked when j is processed: lo and hi already include array i, so last_j - lo and hi - first_j cover both orientations of the pair.

Can the answer be negative?

No. Distances are absolute values and best starts at 0, so equal numbers give 0.

Does the order of the arrays matter?

No. Every pair of arrays is considered exactly when the later one is scanned, so any order gives the same result.

What about arrays with a single element?

Then first and last are the same value, and the same two comparisons still apply.