Description
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.
Example 1:
Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5] Output: 2 Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4). The maximum distance is 2 with pair (2,4).
Example 2:
Input: nums1 = [2,2,2], nums2 = [10,10,1] Output: 1 Explanation: The valid pairs are (0,0), (0,1), and (1,1). The maximum distance is 1 with pair (0,1).
Example 3:
Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25] Output: 2 Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4). The maximum distance is 2 with pair (2,4).
Constraints:
1 <= nums1.length, nums2.length <= 1051 <= nums1[i], nums2[j] <= 105- Both
nums1andnums2are non-increasing.
Solutions
This code finds the maximum distance between indices in two arrays using a two-pointer technique. It maintains two pointers (pos1 and pos2) that iterate through nums1 and nums2 respectively. When nums1[pos1] > nums2[pos2], the current elements can't be validly paired, so it advances pos1 forward (and syncs pos2 to maintain proper indexing). Otherwise, when nums1[pos1] <= nums2[pos2], the elements form a valid pair, and the code calculates the distance (pos2 - pos1) and tracks the maximum. The algorithm continues advancing pos2 to explore other potential pairs, ultimately returning the largest distance found between any two valid index pairs where the value constraint is satisfied.
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxDistance = function(nums1, nums2) {
let pos1 = 0;
let pos2 = 0;
let max = 0;
while (pos1 < nums1.length && pos2 < nums2.length) {
if (nums1[pos1] > nums2[pos2]) {
pos1++;
if (pos2 < pos1) {
pos2 = pos1;
}
continue;
}
max = Math.max(max, pos2 - pos1);
pos2++;
}
return max;
};