Sponsored
Sponsored
This method employs two pointers to traverse both arrays simultaneously. Start with `i` at the beginning of `nums1` and `j` at the beginning of `nums2`. Try to find the largest `j` for each `i` while maintaining the condition `nums1[i] <= nums2[j]` and `i <= j`. The distance `j - i` is calculated and the maximum one is stored. Iterate through both arrays by incrementing `j` while ensuring the condition holds true, otherwise increment `i`.
Time Complexity: O(n + m), where n and m are lengths of nums1 and nums2 respectively.
Space Complexity: O(1), only a few variables are used.
1var maxDistance = function(nums1, nums2) {
2 let i = 0, j = 0, maxDist = 0;
3 while (i < nums1.length && j < nums2.length) {
4 if (nums1[i] <= nums2[j]) {
5 maxDist = Math.max(maxDist, j - i);
6 j++;
7 } else {
8 i++;
9 }
10 }
11 return maxDist;
12};
The JavaScript solution incorporates the two-pointer approach with similar mechanics, using `Math.max` to store the maximal distance.
Utilizing binary search on `nums2` for each element in `nums1` can optimize the search for each valid `j` index. This approach leverages the sorted nature of the arrays. For each element in `nums1`, perform a binary search in `nums2` to find the farthest possible valid `j`.
Time Complexity: O(n * log(m)), where n is the length of nums1 and m is the length of nums2.
Space Complexity: O(1).
public int MaxDistance(int[] nums1, int[] nums2) {
int maxDist = 0;
for (int i = 0; i < nums1.Length; ++i) {
int j = BinarySearch(nums2, i, nums2.Length - 1, nums1[i]);
if (j >= i) {
maxDist = Math.Max(maxDist, j - i);
}
}
return maxDist;
}
private int BinarySearch(int[] arr, int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] < target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
}
C# provides a nested `BinarySearch` method to identify the maximum index `j` that satisfies the conditions, improving efficiency with logarithmic search time per element.