Car Fleet

medium array stack sorting monotonic stack

Problem

n cars drive toward a target at position target. Each car has a position and speed. A faster car bumping into a slower one ahead joins it into a fleet at the slower speed. Return the number of fleets that reach the target.

Inputtarget=12, position=[10,8,0,5,3], speed=[2,4,1,1,3]
Output3
Cars at 10 & 8 form one fleet; 0 & 5 & 3 form fleets per arrival times.

def carFleet(target, position, speed):
    cars = sorted(zip(position, speed), reverse=True)
    stack = []
    for p, s in cars:
        t = (target - p) / s
        if not stack or t > stack[-1]:
            stack.append(t)
    return len(stack)
function carFleet(target, position, speed) {
  const n = position.length;
  const cars = position.map((p, i) => [p, speed[i]]).sort((a, b) => b[0] - a[0]);
  const stack = [];
  for (const [p, s] of cars) {
    const t = (target - p) / s;
    if (stack.length === 0 || t > stack[stack.length - 1]) stack.push(t);
  }
  return stack.length;
}
class Solution {
    public int carFleet(int target, int[] position, int[] speed) {
        int n = position.length;
        Integer[] idx = new Integer[n];
        for (int i = 0; i < n; i++) idx[i] = i;
        Arrays.sort(idx, (a, b) -> position[b] - position[a]);
        Deque<Double> stack = new ArrayDeque<>();
        for (int i : idx) {
            double t = (double)(target - position[i]) / speed[i];
            if (stack.isEmpty() || t > stack.peek()) stack.push(t);
        }
        return stack.size();
    }
}
int carFleet(int target, vector<int>& position, vector<int>& speed) {
    int n = (int)position.size();
    vector<pair<int, int>> cars(n);
    for (int i = 0; i < n; i++) cars[i] = {position[i], speed[i]};
    sort(cars.begin(), cars.end(), greater<>());
    vector<double> st;
    for (auto& [p, s] : cars) {
        double t = (double)(target - p) / s;
        if (st.empty() || t > st.back()) st.push_back(t);
    }
    return (int)st.size();
}
Time: O(n log n) Space: O(n)