Minimum Number of Refueling Stops LeetCode solution in JavaScript

1
var minRefuelStops = function (target, startFuel, stations) {
2
let pq = new MaxPriorityQueue({ compare: (a, b) => b[1] - a[1] });
3
let idx = 0,
4
reachablePosition = startFuel,
5
refuels = 0;
6
// reachablePosition is the farthest position reachable so far
7

8
while (reachablePosition < target) {
9
// While reachablePosition is >= to the current station's position, add the current station to the heap
10
// These stations are all reachable based on the fuel available
11
// Once reachablePosition is less than a station's position, the while loop ends
12
while (idx < stations.length && reachablePosition >= stations[idx][0]) {
13
pq.enqueue([stations[idx][0], stations[idx][1]]);
14
idx++;
15
}
16
// Next, add fuel from the heap in a greedy manner: the station with the most fuel gets added first
17
// All stations in the heap are reachable, so the position is irrelevant
18
if (pq.size()) {
19
let [pos, fuel] = pq.dequeue();
20
reachablePosition += fuel;
21
refuels++;
22
} else break;
23
}
24

25
return reachablePosition >= target ? refuels : -1;
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0