-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimise Maximum Distance between Gas Stations
More file actions
51 lines (45 loc) · 1.28 KB
/
Minimise Maximum Distance between Gas Stations
File metadata and controls
51 lines (45 loc) · 1.28 KB
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
50
51
// Not in leetcode but its the hardest question on Binary Search to solve
#include <bits/stdc++.h>
using namespace std;
int numberOfGasStationsRequired(long double dist, vector<int> &arr) {
int n = arr.size(); // size of the array
int cnt = 0;
for (int i = 1; i < n; i++) {
int numberInBetween = ((arr[i] - arr[i - 1]) / dist);
if ((arr[i] - arr[i - 1]) == (dist * numberInBetween)) {
numberInBetween--;
}
cnt += numberInBetween;
}
return cnt;
}
long double minimiseMaxDistance(vector<int> &arr, int k) {
int n = arr.size(); // size of the array
long double low = 0;
long double high = 0;
//Find the maximum distance:
for (int i = 0; i < n - 1; i++) {
high = max(high, (long double)(arr[i + 1] - arr[i]));
}
//Apply Binary search:
long double diff = 1e-6 ;
while (high - low > diff) {
long double mid = (low + high) / (2.0);
int cnt = numberOfGasStationsRequired(mid, arr);
if (cnt > k) {
low = mid;
}
else {
high = mid;
}
}
return high;
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
int k = 4;
long double ans = minimiseMaxDistance(arr, k);
cout << "The answer is: " << ans << "\n";
return 0;
}