• Time:O(n)
• Space:O(1)

C++

``````class Solution {
public:
int maxDistance(vector<int>& nums1, vector<int>& nums2) {
int ans = 0;
int i = 0;
int j = 0;

while (i < nums1.size() && j < nums2.size())
if (nums1[i] > nums2[j])
++i;
else
ans = max(ans, j++ - i);

return ans;
}
};
``````

JAVA

``````class Solution {
public int maxDistance(int[] nums1, int[] nums2) {
int ans = 0;
int i = 0;
int j = 0;

while (i < nums1.length && j < nums2.length)
if (nums1[i] > nums2[j])
++i;
else
ans = Math.max(ans, j++ - i);

return ans;
}
}
``````

Python

``````class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
ans = 0
i = 0
j = 0

while i < len(nums1) and j < len(nums2):
if nums1[i] > nums2[j]:
i += 1
else:
ans = max(ans, j - i)
j += 1

return ans
``````

• Time:O(n)
• Space:O(1)

C++

``````class Solution {
public:
int maxDistance(vector<int>& nums1, vector<int>& nums2) {
int i = 0;
int j = 0;

for (; i < nums1.size() && j < nums2.size(); ++j)
if (nums1[i] > nums2[j])
++i;

return i == j ? 0 : j - i - 1;
}
};
``````

JAVA

``````class Solution {
public int maxDistance(int[] nums1, int[] nums2) {
int i = 0;
int j = 0;

for (; i < nums1.length && j < nums2.length; ++j)
if (nums1[i] > nums2[j])
++i;

return i == j ? 0 : j - i - 1;
}
}
``````

Python

``````class Solution:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
i = 0
j = 0

while i < len(nums1) and j < len(nums2):
if nums1[i] > nums2[j]:
i += 1
j += 1

return 0 if i == j else j - i - 1
``````