There are n
cars going to the same destination along a one-lane road. The destination is target
miles away.
You are given two integer arrays position
and speed
, both of length n
, where position[i]
is the position of the i-th
car and speed[i]
is the speed of the i-th
car (in miles per hour).
A car can never pass another car ahead of it, but it can catch up to it, forming a car fleet. A car fleet is some non-empty set of cars driving at the same speed. Note that no other cars can join a fleet once it is formed.
Return the number of car fleets that will arrive at the destination.
position
and speed
?
1 <= n <= 10^5
0 <= position[i] < target <= 10^6
0 <= speed[i] <= 10^6
position
and speed
arrays does not matter.#include <vector>
#include <algorithm>
int carFleet(int target, std::vector<int>& position, std::vector<int>& speed) {
int n = position.size();
std::vector<std::pair<int, double>> cars(n);
// Step 1: Calculate the time for each car to reach the target
for (int i = 0; i < n; ++i) {
double time = static_cast<double>(target - position[i]) / speed[i];
cars[i] = {position[i], time};
}
// Step 2: Sort cars by starting position in descending order
std::sort(cars.begin(), cars.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
// Step 3: Count the number of fleets
int fleets = 0;
double last_time = 0.0;
for (const auto& car : cars) {
double current_time = car.second;
if (current_time > last_time) {
// Current car forms a new fleet
fleets++;
last_time = current_time;
}
}
return fleets;
}
Overall, the time complexity of the solution is (O(n \log n)) due to the sorting step.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?