Maximum Distance Between a Pair of Values - Problem
You are given two non-increasing 0-indexed integer arrays nums1 and nums2. Your goal is to find the maximum distance between a pair of valid indices.
A pair of indices (i, j) is considered valid if:
0 <= i < nums1.lengthand0 <= j < nums2.lengthi <= j(index constraint)nums1[i] <= nums2[j](value constraint)
The distance of a valid pair is defined as j - i.
Return the maximum distance of any valid pair. If no valid pairs exist, return 0.
Note: An array is non-increasing if arr[i-1] >= arr[i] for every valid index.
Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
โบ
Output:
2
๐ก Note:
The optimal pair is (i=2, j=4): nums1[2]=5 โค nums2[4]=5, and 2 โค 4, giving distance 4-2=2. Other valid pairs like (0,0) give smaller distances.
example_2.py โ No Valid Pairs
$
Input:
nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
โบ
Output:
2
๐ก Note:
Valid pairs are (2,2), (2,3), (2,4), (3,3), (3,4). The maximum distance is achieved by (2,4) or (3,4), both giving distance 2.
example_3.py โ Single Elements
$
Input:
nums1 = [5], nums2 = [3]
โบ
Output:
0
๐ก Note:
Only one possible pair (0,0), but 5 > 3, so no valid pairs exist. Return 0.
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Place one inspector at the start of first row, another at the end of second row
2
Valid Connection
If current buildings can connect, record distance and try for longer bridge by moving second inspector left
3
Invalid Connection
If buildings can't connect, move first inspector right to find a shorter building
4
Optimal Result
Continue until inspectors meet or exhaust possibilities, keeping track of maximum distance
Key Takeaway
๐ฏ Key Insight: The two pointers technique leverages the non-increasing property of both arrays to efficiently find the maximum valid distance without checking all possible pairs.
Time & Space Complexity
Time Complexity
O(n log m)
For each element in nums1 (n elements), we perform binary search on nums2 (log m time)
โก Linearithmic
Space Complexity
O(1)
Only using variables for binary search bounds and maximum distance
โ Linear Space
Constraints
- 1 โค nums1.length, nums2.length โค 105
- 1 โค nums1[i], nums2[i] โค 105
- nums1 and nums2 are both non-increasing
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code