-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarFleetII.cpp
More file actions
24 lines (23 loc) · 797 Bytes
/
carFleetII.cpp
File metadata and controls
24 lines (23 loc) · 797 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Source: https://leetcode.com/problems/car-fleet-ii/
// Author: Miao Zhang
// Date: 2021-06-07
class Solution {
public:
vector<double> getCollisionTimes(vector<vector<int>>& cars) {
auto collide = [&] (int i, int j) -> double {
return static_cast<double>(cars[j][0] - cars[i][0]) / (cars[i][1] - cars[j][1]);
};
int n = cars.size();
vector<double> res(n, -1);
stack<int> s;
for (int i = n - 1; i >= 0; i--) {
while (!s.empty() && (cars[i][1] <= cars[s.top()][1] ||
(s.size() > 1 && collide(i, s.top()) > res[s.top()]))) {
s.pop();
}
res[i] = s.empty() ? -1 : collide(i, s.top());
s.push(i);
}
return res;
}
};