Maximum Distance in Arrays — LeetCode 624 Python Solution
- Problem
- #624
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m), where m is the number of arrays |
| Space | O(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.