Skip to content

Commit d38c415

Browse files
authored
Create 871. Minimum Number of Refueling Stops
1 parent 744e7c6 commit d38c415

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public int minRefuelStops(int target, int startFuel, int[][] stations) {
3+
int n=stations.length;
4+
long[] dp = new long[n+1];
5+
dp[0]=startFuel;
6+
7+
for(int i=0;i<n;i++){
8+
for(int refill = i;refill>=0 && dp[refill]>=stations[i][0];refill--){
9+
dp[refill+1] = Math.max(dp[refill+1],dp[refill] + stations[i][1]);
10+
}
11+
}
12+
13+
for(int i=0;i<=n;i++){
14+
if(dp[i]>=target){
15+
return i;
16+
}
17+
}
18+
19+
return -1;
20+
}
21+
}
22+
23+
class Solution {
24+
public int minRefuelStops(int target, int startFuel, int[][] stations) {
25+
int n=stations.length;
26+
PriorityQueue<int[]> pq= new PriorityQueue<>((a,b) -> b[1]-a[1]);
27+
28+
int refill =0,i=0;
29+
int distance = startFuel;
30+
31+
while(distance<target){
32+
while(i<n && distance >= stations[i][0]){
33+
pq.offer(stations[i]);
34+
i++;
35+
}
36+
37+
if(pq.isEmpty()) return -1;
38+
39+
distance += pq.remove()[1];
40+
refill++;
41+
}
42+
43+
return refill;
44+
}
45+
}

0 commit comments

Comments
 (0)