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
.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[j] <= 105
Both
nums1
andnums2
are non-increasing.
这个题,很经典的双指针,而且有点2sum的感觉,只是这里的判断条件不是sum == target,而是i <= j && nums1[i] <= nums2[j]。如果符合条件,我们算max,如果不符合的时候,我们移动指针。因为条件限制了i <= j,然后max是算j - i,所以j一定要比i大,不符合条件,同时向右。然后还有一种情况是,i <= j, j到了结尾了。这种情况也不需要特判,因为j - i求的是max,就算继续移动i向右也不可能得到更大的值。所以两个条件都归纳到else里了。T:O(n + m),S: O(1)
Last updated