Optimal: sort and track fleet arrival times
Time O(n log n) Space O(n)Sort by position descending. Walk from the car nearest the target. Its time alone is (target − pos) / speed. If it's greater than the current leading fleet's time, it can't catch up: it starts a new fleet. Otherwise it merges and adopts that fleet's time. (This is a stack of fleet times where only the top matters.)
import java.util.Arrays;
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> Integer.compare(position[b], position[a])); // closest first
int fleets = 0;
double leadTime = 0;
for (int i : order) {
double time = (double) (target - position[i]) / speed[i];
if (time > leadTime) { // can't catch the fleet ahead: new fleet
fleets++;
leadTime = time;
}
}
return fleets;
}
}Verdict: Sorting dominates; the scan is linear.