Minimum Speed to Arrive on Time LeetCode solution in JavaScript

1
var minSpeedOnTime = function (dist, hour) {
2
let left = 1,
3
right = 10000000,
4
speed,
5
sum,
6
ans = -1;
7
while (left <= right) {
8
//We need to return the minimum positive integer speed (in kilometers per hour) that all the trains must travel. So speed will always be an integer ranging from 1 to 10000000 as per the question description.
9
speed = left + Math.floor((right - left) / 2);
10
sum = 0;
11
for (let i = 0; i < dist.length - 1; i++) {
12
sum += Math.ceil(dist[i] / speed);
13
}
14
sum += dist[dist.length - 1] / speed; //For the last train we need not to do Math.ceil
15
if (sum <= hour) {
16
//sum(time taken is less than the required time, so it can be our answer, but we will keep looking for the another smaller speed until left<=right)
17
ans = speed;
18
right = speed - 1;
19
} else {
20
left = speed + 1;
21
}
22
}
23
return ans;
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0