774. Minimize Max Distance to Gas Station
Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.500000// Binary Search
double minmaxGasDist(vector<int>& stations, int K) { // time: O(n * log(stations[n - 1] - stations[0])); space: O(1)
int n = stations.size();
double low = 0, high = stations.back() - stations.front();
while (low + 1e-6 < high) {
double mid = (low + high) / 2.0;
int count = 0;
for (int i = 0; i < n - 1; ++i) {
count += ceil((stations[i + 1] - stations[i]) / mid) - 1;
}
if (count > K) low = mid;
else high = mid;
}
return low;
}Last updated