MediumNo. 0624

Maximum Distance in Arrays — LeetCode 624 Python Solution

Pattern
Greedy
Topics
Greedy, Array
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

PythonSolution
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

Time
O(m)where m is the number of arrays
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0630Course Schedule IIIHard
0011Container With Most WaterMedium
0134Gas StationMedium
0135CandyHard
0179Largest NumberMedium
0324Wiggle Sort IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.