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.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5int maxDistance(vector<int>& nums1, vector<int>& nums2) {
6 int i = 0, j = 0, maxDist = 0;
7 while (i < nums1.size() && j < nums2.size()) {
8 if (nums1[i] <= nums2[j]) {
9 maxDist = max(maxDist, j - i);
10 j++;
11 } else {
12 i++;
13 }
14 }
15 return maxDist;
16}
In this C++ implementation, the idea is identical to the C solution but uses the `std::vector` class. The loop iterates through both vectors with similar logic, updating the maximum distance whenever the conditions are satisfied.
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).
The Python solution incorporates binary search to quickly locate the farthest valid `j` for each `i`, enhancing performance while maintaining simplicity.