-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimizeMaxDistance.java
More file actions
32 lines (26 loc) · 884 Bytes
/
MinimizeMaxDistance.java
File metadata and controls
32 lines (26 loc) · 884 Bytes
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
package Searching;
public class MinimizeMaxDistance {
public static int noOfGasStationsBetween(int[] arr, double dist) {
int cnt = 0, n = arr.length;
for (int i = 0; i < n - 1; i++) {
double stationsInBetween = (arr[i + 1] - arr[i]) / dist;
cnt += stationsInBetween;
}
return cnt;
}
public static double findSmallestMaxDist(int[] arr, int k) {
int n = arr.length;
double maxi = Integer.MIN_VALUE;
for (int i = 0; i < n - 1; i++)
maxi = Math.max(maxi, arr[i + 1] - arr[i]);
double low = 0, high = maxi, diff = 1e-6;
while (high - low > diff) {
double mid = low + (high - low) / 2;
if (noOfGasStationsBetween(arr, mid) <= k)
high = mid;
else
low = mid;
}
return high;
}
}