-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0853-car-fleet.cpp
37 lines (30 loc) · 1.06 KB
/
0853-car-fleet.cpp
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
/*
n cars 1 road, diff pos/speeds, faster cars slow down -> car fleet, return # fleets
Ex. target = 12, pos = [10,8,0,5,3], speeds = [2,4,1,1,3] -> 3 (10 & 8, 0, 5 & 3)
Sort by start pos, calculate time for each car to finish, loop backwards
If car behind finishes faster then catches up to fleet, else creates new fleet
Time: O(n log n)
Speed: O(n)
*/
class Solution {
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
int n = position.size();
vector<pair<int, double>> cars;
for (int i = 0; i < n; i++) {
double time = (double) (target - position[i]) / speed[i];
cars.push_back({position[i], time});
}
sort(cars.begin(), cars.end());
double maxTime = 0.0;
int result = 0;
for (int i = n - 1; i >= 0; i--) {
double time = cars[i].second;
if (time > maxTime) {
maxTime = time;
result++;
}
}
return result;
}
};