目标
给你两个 非递增 的整数数组 nums1 和 nums2 ,数组下标均 从 0 开始 计数。
下标对 (i, j) 中 0 <= i < nums1.length 且 0 <= j < nums2.length 。如果该下标对同时满足 i <= j 且 nums1[i] <= nums2[j] ,则称之为 有效 下标对,该下标对的 距离 为 j - i 。
返回所有 有效 下标对 (i, j) 中的 最大距离 。如果不存在有效下标对,返回 0 。
一个数组 arr ,如果每个 1 <= i < arr.length 均有 arr[i-1] >= arr[i] 成立,那么该数组是一个 非递增 数组。
示例 1:
输入:nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
输出:2
解释:有效下标对是 (0,0), (2,2), (2,3), (2,4), (3,3), (3,4) 和 (4,4) 。
最大距离是 2 ,对应下标对 (2,4) 。
示例 2:
输入:nums1 = [2,2,2], nums2 = [10,10,1]
输出:1
解释:有效下标对是 (0,0), (0,1) 和 (1,1) 。
最大距离是 1 ,对应下标对 (0,1) 。
示例 3:
输入:nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
输出:2
解释:有效下标对是 (2,2), (2,3), (2,4), (3,3) 和 (3,4) 。
最大距离是 2 ,对应下标对 (2,4) 。
说明:
- 1 <= nums1.length <= 10^5
- 1 <= nums2.length <= 10^5
- 1 <= nums1[i], nums2[j] <= 10^5
- nums1 和 nums2 都是 非递增 数组
思路
有两个非递增的整数数组 nums1 和 nums2,返回有效下标对的最大距离,如果不存在有效下标对,返回 0。有效下标对 (i, j) 需要满足 i <= j && nums1[i] <= nums2[j]。
二分查找 nums2 大于等于 nums1[i] 的最大下标,记录 j - i 的最大值。
代码
/**
* @date 2026-04-19 23:44
*/
public class MaxDistance1855 {
public int maxDistance(int[] nums1, int[] nums2) {
int res = 0;
for (int i = 0; i < nums1.length; i++) {
int j = upperBound(nums2, i, nums1[i]);
res = Math.max(res, j - i);
}
return res;
}
public int upperBound(int[] arr, int l, int target) {
int r = arr.length - 1;
int m = l + (r - l) / 2;
while (l <= r) {
if (arr[m] >= target) {
l = m + 1;
} else {
r = m - 1;
}
m = l + (r - l) / 2;
}
return r;
}
}
性能











