-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC853_CarFleet.java
More file actions
29 lines (27 loc) · 929 Bytes
/
LC853_CarFleet.java
File metadata and controls
29 lines (27 loc) · 929 Bytes
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
package practise.leetCode;
import java.util.Arrays;
import java.util.Stack;
public class LC853_CarFleet {
public static void main(String[] args) {
int target = 12;
int[] position = {10,8,0,5,3}, speed = {2,4,1,1,3};
System.out.println(carFleet(target, position, speed));
}
public static int carFleet(int target, int[] position, int[] speed) {
int n = position.length;
int[][] cars = new int[n][2];
for (int i = 0; i < n; i++) {
cars[i][0] = position[i];
cars[i][1] = speed[i];
}
Arrays.sort(cars, (a, b) -> b[0] - a[0]);
Stack<Double> stack = new Stack<>();
for (int i = 0; i < n; i++) {
double time = (double)(target - cars[i][0]) / cars[i][1];
if (stack.isEmpty() || time > stack.peek()) {
stack.push(time);
}
}
return stack.size();
}
}