Skip to content

Commit 706561e

Browse files
authored
Update minimize-max-distance-to-gas-station.cpp
1 parent 7250780 commit 706561e

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

C++/minimize-max-distance-to-gas-station.cpp

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,23 @@
44
class Solution {
55
public:
66
double minmaxGasDist(vector<int>& stations, int K) {
7-
double left = 0.0;
8-
double right = 1e8;
7+
const auto& check = [&](double x) {
8+
int total = 0;
9+
for (int i = 0; i + 1 < stations.size(); ++i) {
10+
total += ceil((stations[i + 1] - stations[i]) / x) - 1;
11+
}
12+
return total <= K;
13+
};
14+
15+
double left = 0.0, right = stations.back() - stations.front();
916
while (right - left > 1e-6) {
1017
const auto mid = left + (right - left) / 2.0;
11-
if (possible(stations, K, mid)) {
18+
if (check(mid)) {
1219
right = mid;
1320
} else {
1421
left = mid;
1522
}
1623
}
1724
return left;
1825
}
19-
20-
private:
21-
bool possible(const vector<int>& stations, int K, double guess) {
22-
int sum = 0;
23-
for (int i = 0; i + 1 < stations.size(); ++i) {
24-
sum += int((stations[i + 1] - stations[i]) / guess);
25-
}
26-
return sum <= K;
27-
}
2826
};

0 commit comments

Comments
 (0)