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
Maximum Distance Between a Pair of Values INPUT nums1 (non-increasing) 55 i=0 30 i=1 5 i=2 nums2 (non-increasing) 100 j=0 20 j=1 10 j=2 5 j=3 Valid Pair Conditions: i <= j nums1[i] <= nums2[j] Distance = j - i Find: max(j - i) ALGORITHM STEPS 1 Two Pointers Setup i=0 for nums1, j=0 for nums2 2 Check Valid Pair If nums1[i] <= nums2[j] 3 Update Max Distance maxDist = max(maxDist, j-i) 4 Move Pointers Valid: j++, Invalid: i++ Execution Trace: i=0,j=0: 55<=100 OK d=0 i=0,j=1: 55>20 SKIP i++ i=1,j=1: 30>20 SKIP i++ i=2,j=1: 5<=20 OK d=1 i=2,j=2: 5<=10 OK d=0 i=2,j=3: 5<=5 OK d=1 maxDist = 1 FINAL RESULT Best Valid Pair Found 55 30 5 i=2 100 20 j=3 10 5 Pair (i=2, j=3) 5 <= 20 [OK] d = 3-2 = 1 Output 1 Key Insight: Two-pointer technique works because both arrays are non-increasing (sorted in descending order). When nums1[i] > nums2[j], moving j right won't help (nums2[j] only gets smaller), so we increment i. Time Complexity: O(n+m) where n and m are array lengths. Space Complexity: O(1). TutorialsPoint - Maximum Distance Between a Pair of Values | Two Pointer Approach
Asked in
Amazon 15 Microsoft 12 Google 8
18.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen