Skip to content

Commit 2c87722

Browse files
authored
Create minimum-number-of-refueling-stops.cpp
1 parent 39ce8f3 commit 2c87722

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
7+
priority_queue<int> max_heap;
8+
stations.push_back(vector<int>{target, numeric_limits<int>::min()});
9+
10+
int result = 0, prev = 0;
11+
for (const auto& station : stations) {
12+
startFuel -= station[0] - prev;
13+
while (!max_heap.empty() && startFuel < 0) {
14+
startFuel += max_heap.top(); max_heap.pop();
15+
++result;
16+
}
17+
if (startFuel < 0) {
18+
return -1;
19+
}
20+
max_heap.emplace(station[1]);
21+
prev = station[0];
22+
}
23+
return result;
24+
}
25+
};

0 commit comments

Comments
 (0)