Maximum Distance Between a Pair of Values - Problem
You are given two non-increasing 0-indexed integer arrays nums1 and nums2.
A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i.
Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.
An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [55,30,5], nums2 = [100,20,10,5]
›
Output:
1
💡 Note:
The valid pairs are (0,0), (2,2), and (2,3). The pair (2,3) has the maximum distance of 3-2=1.
Example 2 — No Valid Pairs
$
Input:
nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
›
Output:
2
💡 Note:
Valid pairs are (3,3) and (3,4). The maximum distance is 4-3=1. Actually, (3,3) gives 0 and (3,4) gives 1, but we also have (2,4) since 19≤25, giving distance 2.
Example 3 — Single Elements
$
Input:
nums1 = [1], nums2 = [1]
›
Output:
0
💡 Note:
Only one valid pair (0,0) with distance 0-0=0.
Constraints
- 1 ≤ nums1.length, nums2.length ≤ 105
- 1 ≤ nums1[i], nums2[i] ≤ 105
- nums1 and nums2 are non-increasing
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
Two non-increasing arrays nums1 and nums2
2
Valid Pairs
Find pairs (i,j) where i≤j and nums1[i]≤nums2[j]
3
Maximum Distance
Return the largest j-i value found
Key Takeaway
🎯 Key Insight: Use the sorted property to efficiently find pairs without checking all combinations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code