-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-MinimumNumberOfRefuelingStops.cpp
More file actions
45 lines (32 loc) · 1.07 KB
/
LeetCode-MinimumNumberOfRefuelingStops.cpp
File metadata and controls
45 lines (32 loc) · 1.07 KB
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
40
41
42
43
44
45
class Solution {
int canReach(vector<vector<int>>& stations) {
int fuel = stations[0][1];
int count = 0;
priority_queue<int> pq;
for (int i = 1; i < stations.size(); ++i) {
int dist = stations[i][0] - stations[i-1][0];
if (dist <= fuel) {
fuel -= dist;
pq.push(stations[i][1]);
continue;
}
while (!pq.empty() && fuel < dist) {
fuel += pq.top();
++count;
pq.pop();
}
if (fuel < dist) {
return -1;
}
fuel -= dist;
pq.push(stations[i][1]);
}
return count;
}
public:
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
stations.insert(stations.begin(), {0, startFuel});
stations.push_back({target, 0});
return canReach(stations);
}
};