LeetCode 1855. Maximum Distance Between a Pair of Values Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1855. Maximum Distance Between a Pair of Values

Description

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:

Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
Output: 2
Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).

Example 2:

Input: nums1 = [2,2,2], nums2 = [10,10,1]
Output: 1
Explanation: The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).

Example 3:

Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
Output: 2
Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).

 

Constraints:

  • 1 <= nums1.length, nums2.length <= 105
  • 1 <= nums1[i], nums2[j] <= 105
  • Both nums1 and nums2 are non-increasing.

Solutions

Solution 1: Binary Search

Assume the lengths of nums1 and nums2 are m and n respectively.

Traverse array nums1, for each number nums1[i], perform a binary search for numbers in nums2 in the range [i,n), find the last position j that is greater than or equal to nums1[i], calculate the distance between this position and i, and update the maximum distance value ans.

The time complexity is O(m × log n), where m and n are the lengths of nums1 and nums2 respectively. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: ans = 0 nums2 = nums2[::-1] for i, v in enumerate(nums1): j = len(nums2) - bisect_left(nums2, v) - 1 ans = max(ans, j - i) return ans(code-box)

Solution 2

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def maxDistance(self, nums1: List[int], nums2: List[int]) -> int: m, n = len(nums1), len(nums2) ans = i = j = 0 while i < m: while j < n and nums1[i] <= nums2[j]: j += 1 ans = max(ans, j - i - 1) i += 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !