-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathMinimumNumberofRefuelingStops.java
39 lines (34 loc) · 1.11 KB
/
MinimumNumberofRefuelingStops.java
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
class Solution {
// TC : O(nlogn)
// SC : O(n)
public int minRefuelStops(int target, int startFuel, int[][] stations) {
int xCurrent = startFuel;
int noOfStopsNeeded = 0;
// Max Heap on the basis of fuel value
PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) ->(b-a));
for(int[] station: stations){
int nextStationX = station[0];
int fuelAtStation = station[1];
while(xCurrent < nextStationX){// exhauted all your fuel
if(pq.isEmpty()){
return -1;
}
int maxFuel = pq.poll();
xCurrent= xCurrent+ maxFuel;
noOfStopsNeeded++;
}
pq.offer(fuelAtStation);
}
// not yet reached the destination
while(xCurrent< target){
if(pq.isEmpty()){
return -1;
}
// still have unvisited gas stations
int maxFuel = pq.poll();
xCurrent= xCurrent+ maxFuel;
noOfStopsNeeded++;
}
return noOfStopsNeeded;
}
}