-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCar Fleet.java
36 lines (28 loc) · 950 Bytes
/
Car Fleet.java
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
class Solution {
public static class Car {
public int position;
public int speed;
public Car(int position, int speed) {
this.position = position;
this.speed = speed;
}
}
public int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
Car[] cars = new Car[n];
for (int i = 0; i < n; i++) {
cars[i] = new Car(position[i], speed[i]);
}
Arrays.sort(cars, (x, y) -> Integer.compare(y.position, x.position));
int fleetsCount = 0;
double lastCarArrivalTime = 0;
for (Car car : cars) {
double arrivalTime = (target - car.position) / (double) car.speed;
if (arrivalTime > lastCarArrivalTime) {
fleetsCount++; // new fleet formed
lastCarArrivalTime = arrivalTime;
}
}
return fleetsCount;
}
}