[LeetCode] Maximum Distance Between a Pair of Values

1855. Maximum Distance Between a Pair of Values

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxDistance(vector<int>& nums1, vector<int>& nums2) {
int dis = 0, i = 0, j = 0;
while(i < nums1.size() and j < nums2.size()) {
while(j < nums2.size() and nums2[j] >= nums1[i]) j++;
if(j > 0 and nums2[j-1] >= nums1[i])
dis = max(dis, j - i - 1);
i++;
}
return dis;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/28/PS/LeetCode/maximum-distance-between-a-pair-of-values/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.