Skip to content

Instantly share code, notes, and snippets.

@xiaq
Created June 12, 2021 20:23
Show Gist options
  • Save xiaq/0fd7c14ebbb746cb575d99e5b997638f to your computer and use it in GitHub Desktop.
Save xiaq/0fd7c14ebbb746cb575d99e5b997638f to your computer and use it in GitHub Desktop.
class Solution {
public int minRefuelStops(int target, int startFuel, int[][] stations) {
int p = 0; // position
int i = 0; // index of first unreachable station
var q = new PriorityQueue<Integer>(stations.length/2 + 1, Collections.reverseOrder());
q.add(startFuel);
int refills = -1; // we count initial fuel as a filling too, so initialize to -1
while (p < target) {
if (q.isEmpty()) {
return -1;
}
p += q.poll();
refills++;
while (i < stations.length && stations[i][0] <= p) {
q.add(stations[i][1]);
i++;
}
}
return refills;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment