Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Stack & Queue

Car Fleet

Medium · Stack & Queue · Asked at Google, Amazon, Uber, Microsoft

n cars drive along one lane towards target. Car i starts at position[i] (all different) with speed speed[i]. A car can never pass another: when it catches up it slows down and they move on together as one fleet. A car that catches up exactly at the target still joins that fleet. Print the number of fleets that arrive at the target.

Input

First line: n target. Second line: the positions. Third line: the speeds.

Output

The number of fleets.

Constraints

Sort cars by position, closest to the target first, and compute each car’s arrival time if alone. A car forms a new fleet only when it would arrive strictly later than the fleet ahead of it. Compare times as fractions (cross-multiply) to avoid rounding.

Example 1

Input

5 12
10 8 0 5 3
2 4 1 1 3

Output

3

Example 2

Input

1 10
3
3

Output

1

Hints

  1. Cars never pass, so only the car directly ahead can block you.
  2. Process cars from the one closest to the target backwards.
  3. Compare arrival times: a car arriving no later than the fleet ahead joins it.

Approach

Sort cars by position, largest first. Track the arrival time of the fleet just ahead. For each car, its solo time is (target − position) / speed. If it is strictly greater than the fleet ahead, it can never catch up — a new fleet begins and its time becomes the new reference. Otherwise it merges. Compare times by cross-multiplying distances and speeds (products up to 10^12) to avoid floating-point ties.

Complexity: O(n log n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    long long target;
    cin >> n >> target;
    vector<pair<long long, long long>> cars(n); // (position, speed)
    for (auto &c : cars) cin >> c.first;
    for (auto &c : cars) cin >> c.second;
    sort(cars.rbegin(), cars.rend());
    int fleets = 0;
    long long aheadDist = -1, aheadSpeed = 1;
    for (auto &c : cars) {
        long long d = target - c.first;
        // this car's time d / speed > ahead's time aheadDist / aheadSpeed ?
        if (aheadDist < 0 || d * aheadSpeed > aheadDist * c.second) {
            fleets++;
            aheadDist = d;
            aheadSpeed = c.second;
        }
    }
    cout << fleets << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n, target = data[0], data[1]
pos = data[2 : 2 + n]
speed = data[2 + n : 2 + 2 * n]
cars = sorted(zip(pos, speed), reverse=True)
fleets = 0
ahead = None  # (distance, speed) of the fleet ahead
for p, s in cars:
    d = target - p
    if ahead is None or d * ahead[1] > ahead[0] * s:
        fleets += 1
        ahead = (d, s)
print(fleets)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        long target = (long) in.nval;
        long[][] cars = new long[n][2];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            cars[i][0] = (long) in.nval;
        }
        for (int i = 0; i < n; i++) {
            in.nextToken();
            cars[i][1] = (long) in.nval;
        }
        Arrays.sort(cars, (a, b) -> Long.compare(b[0], a[0]));
        int fleets = 0;
        long aheadDist = -1, aheadSpeed = 1;
        for (long[] c : cars) {
            long d = target - c[0];
            if (aheadDist < 0 || d * aheadSpeed > aheadDist * c[1]) {
                fleets++;
                aheadDist = d;
                aheadSpeed = c[1];
            }
        }
        System.out.println(fleets);
    }
}

Solve Car Fleet online · All practice problems