-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMaximumDistanceBetweenAPairOfValues.java
49 lines (43 loc) · 1.39 KB
/
MaximumDistanceBetweenAPairOfValues.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/*/
/*O(nlogn) solution*/
class Solution {
public int maxDistance(int[] nums1, int[] nums2) {
int n1 = nums1.length, n2 = nums2.length, i, j, maxJ, maxDiff = 0, limit = Math.min(n1,n2);
for (i = 0; i < limit; ++i) //for each element in nums1
{
if (nums1[i] <= nums2[i]) //only if nums1[i] <= nums2[i]
{
maxJ = binarySearch(nums2,i,n2-1,nums1[i]); //find the last index in nums2 which is larger than nums1[i]
if (maxJ-i > maxDiff) maxDiff = maxJ-i;
}
}
return maxDiff;
}
public int binarySearch(int[] arr, int low, int high, int target)
{
int mid, n2 = high;
while (low <= high)
{
mid = low+((high-low)/2);
if (target <= arr[mid] && (mid == n2 || target > arr[mid+1])) return mid;
else if (target <= arr[mid]) low = mid+1;
else high = mid-1;
}
return -1;
}
}
/*Efficient Solution*/
class Solution
{
public int maxDistance(int[] nums1, int[] nums2)
{
int n1 = nums1.length, n2 = nums2.length, i = 0, j = 0;
while (i < n1 && j < n2)
{
while (j < n2-1 && nums2[j+1] >= nums1[i]) j++;
i++;
j++;
}
return j-i;
}
}