Maximum Distance in Arrays — LeetCode 624 Python Solution

MediumGreedyArray
Problem
#624
Pattern
Greedy
Reading time
2 min

The problem

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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(m), where m is the number of arrays
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 624. Maximum Distance in Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 624. Maximum Distance in Arrays?
LeetCode 624. Maximum Distance in Arrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 624. Maximum Distance in Arrays?
The Python solution on this page runs in O(m), where m is the number of arrays.
What is the space complexity of LeetCode 624. Maximum Distance in Arrays?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 624. Maximum Distance in Arrays cover?
LeetCode 624. Maximum Distance in Arrays is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview