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 themaximum distance of any valid pair (i, j). If there are no valid pairs, return0.
An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Input: nums1 =[55,30,5,4,2], nums2 =[100,20,10,10,5]Output: 2Explanation: The valid pairs are(0,0),(2,2),(2,3),(2,4),(3,3),(3,4), and (4,4).The maximum distance is2withpair(2,4).
Input: nums1 =[30,29,19,5], nums2 =[25,25,25,25,25]Output: 2Explanation: The valid pairs are(2,2),(2,3),(2,4),(3,3), and (3,4).The maximum distance is2withpair(2,4).
Since both arrays are non-increasing, we can use two pointers to efficiently find the maximum distance for valid pairs. For each index in nums1, we move the pointer in nums2 as far as possible while maintaining the constraints.
classSolution {
public:int maxDistance(vector<int>& nums1, vector<int>& nums2) {
int ans =0, j =0, n1 = nums1.size(), n2 = nums2.size();
for (int i =0; i < n1; ++i) {
while (j < n2 && nums2[j] >= nums1[i]) ++j;
if (j-1>= i) ans = max(ans, j-1-i);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funcmaxDistance(nums1 []int, nums2 []int) int {
ans, j:=0, 0n1, n2:= len(nums1), len(nums2)
fori:=0; i < n1; i++ {
forj < n2&&nums2[j] >=nums1[i] {
j++ }
ifj-1>=i&&j-1-i > ans {
ans = j-1-i }
}
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintmaxDistance(int[] nums1, int[] nums2) {
int ans = 0, j = 0, n1 = nums1.length, n2 = nums2.length;
for (int i = 0; i < n1; i++) {
while (j < n2 && nums2[j]>= nums1[i]) j++;
if (j-1 >= i) ans = Math.max(ans, j-1-i);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaxDistance(nums1: IntArray, nums2: IntArray): Int {
var ans = 0var j = 0for (i in nums1.indices) {
while (j < nums2.size && nums2[j] >= nums1[i]) j++if (j-1>= i) ans = maxOf(ans, j-1-i)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaxDistance(self, nums1: list[int], nums2: list[int]) -> int:
ans =0 j =0 n1, n2 = len(nums1), len(nums2)
for i in range(n1):
while j < n2 and nums2[j] >= nums1[i]:
j +=1if j-1>= i:
ans = max(ans, j-1-i)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnmax_distance(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
letmut ans =0;
letmut j =0;
let n1 = nums1.len();
let n2 = nums2.len();
for i in0..n1 {
while j < n2 && nums2[j] >= nums1[i] {
j +=1;
}
if j >0&& j-1>= i {
ans = ans.max(j-1-i);
}
}
ans asi32 }
}
1
2
3
4
5
6
7
8
9
10
classSolution {
maxDistance(nums1: number[], nums2: number[]):number {
letans=0, j=0, n1=nums1.length, n2=nums2.length;
for (leti=0; i<n1; i++) {
while (j<n2&&nums2[j] >=nums1[i]) j++;
if (j-1>=i) ans= Math.max(ans, j-1-i);
}
returnans;
}
}