#1855
Maximum Distance Between a Pair of Values
MediumArrayTwo PointersBinary SearchTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
By leveraging the non-increasing property of the arrays, we can use a two-pointer technique to efficiently find the maximum distance without checking every pair.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, i for nums1 and j for nums2, both starting at 0.
- 2Step 2: While i is less than the length of nums1 and j is less than the length of nums2, check if nums1[i] <= nums2[j].
- 3Step 3: If valid, calculate the distance j - i and update max_distance. Increment j to check further elements in nums2.
- 4Step 4: If not valid, increment i to check the next element in nums1.
- 5Step 5: Return max_distance after the loop.
solution.py12 lines
1# Full working Python code
2
3def maxDistance(nums1, nums2):
4 max_distance = 0
5 i, j = 0, 0
6 while i < len(nums1) and j < len(nums2):
7 if nums1[i] <= nums2[j]:
8 max_distance = max(max_distance, j - i)
9 j += 1
10 else:
11 i += 1
12 return max_distanceℹ
Complexity note: This complexity is linear because we are only traversing each array once with the two pointers, making it much more efficient than the brute force approach.
- 1Both arrays are sorted in non-increasing order, allowing for efficient searching.
- 2Using two pointers helps avoid unnecessary comparisons and reduces time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.