-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0774-minimize-max-distance-to-gas-station.js
More file actions
49 lines (43 loc) · 1.21 KB
/
0774-minimize-max-distance-to-gas-station.js
File metadata and controls
49 lines (43 loc) · 1.21 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
/**
* 774. Minimize Max Distance to Gas Station
* https://leetcode.com/problems/minimize-max-distance-to-gas-station/
* Difficulty: Hard
*
* You are given an integer array stations that represents the positions of the gas stations
* on the x-axis. You are also given an integer k.
*
* You should add k new gas stations. You can add the stations anywhere on the x-axis, and
* not necessarily on an integer position.
*
* Let penalty() be the maximum distance between adjacent gas stations after adding the k
* new stations.
*
* Return the smallest possible value of penalty(). Answers within 10-6 of the actual answer
* will be accepted.
*/
/**
* @param {number[]} stations
* @param {number} k
* @return {number}
*/
var minmaxGasDist = function(stations, k) {
const gaps = [];
for (let i = 1; i < stations.length; i++) {
gaps.push(stations[i] - stations[i - 1]);
}
let left = 0;
let right = Math.max(...gaps);
while (right - left > 1e-6) {
const mid = (left + right) / 2;
let stationsNeeded = 0;
for (const gap of gaps) {
stationsNeeded += Math.floor(gap / mid);
}
if (stationsNeeded <= k) {
right = mid;
} else {
left = mid;
}
}
return right;
};