774 Minimize Max Distance to Gas Station
1. Question
Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.5000002. Implementation
3. Time & Space Complexity
Last updated
Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.500000Last updated
class Solution {
public double minmaxGasDist(int[] stations, int K) {
double end = Integer.MIN_VALUE;
for (int i = 1; i < stations.length; i++) {
end = Math.max(end, stations[i] - stations[i - 1]);
}
double start = 0, mid = 0;
while (end - start > 1e-6) {
mid = start + (end - start) / 2;
if (isValid(stations, K, mid)) {
end = mid;
}
else {
start = mid;
}
}
return start;
}
public boolean isValid(int[] stations, int K, double target) {
int count = 0;
for (int i = 1; i < stations.length; i++) {
count += (stations[i] - stations[i - 1]) / target;
}
return count <= K;
}
}