Magicsheet logo

Maximum Distance in Arrays

Medium
12.5%
Updated 8/1/2025

Maximum Distance in Arrays

1. What is this problem about?

In the Maximum Distance in Arrays coding problem, you are given several sorted arrays. You need to pick two integers from two different arrays such that the absolute difference between them is maximized. You cannot pick both integers from the same array. This is an interesting variation of finding the range of a dataset, but with the constraint of 'different sources'.

2. Why is this asked in interviews?

Companies like Microsoft, Google, and Amazon ask this to see if candidates can handle multiple data streams efficiently. It tests your ability to maintain global state (like the current global min and max) while iterating through a list of collections. The challenge lies in ensuring you don't pick two elements from the same array while still achieving the global maximum difference.

3. Algorithmic pattern used

This follows a Greedy interview pattern. As you iterate through the list of arrays, you keep track of the minimum and maximum values seen in all previous arrays. For the current array, you calculate two potential distances: the difference between the current array's maximum and the previous global minimum, and the difference between the previous global maximum and the current array's minimum. You update your overall maximum distance with these values and then update your global min/max for the next iteration.

4. Example explanation

Suppose we have three arrays: Array 1: [1, 2, 3] Array 2: [4, 5] Array 3: [1, 2, 8]

  • Start with Array 1: Global Min = 1, Global Max = 3.
  • Process Array 2:
    • Dist 1: |5 - 1| = 4.
    • Dist 2: |4 - 3| = 1.
    • Max Dist = 4. Update Global Min = min(1, 4) = 1, Global Max = max(3, 5) = 5.
  • Process Array 3:
    • Dist 1: |8 - 1| = 7.
    • Dist 2: |1 - 5| = 4.
    • Max Dist = max(4, 7, 4) = 7. Update Global Min = 1, Global Max = 8. Result is 7.

5. Common mistakes candidates make

The most common mistake is sorting all elements from all arrays into one giant list and picking the max and min. This fails if the max and min come from the same original array. Another mistake is not updating the global min and max correctly at each step, or only comparing the current array's min/max with each other.

6. Interview preparation tip

For the Maximum Distance in Arrays coding problem, practice the 'streaming' approach. Instead of looking at all data at once, think about what information you need to keep from 'the past' to make the best decision for 'the present'. This is a fundamental concept in many efficient array algorithms.

Similar Questions