Formatted question description: https://leetcode.ca/all/1776.html

# 1776. Car Fleet II

Hard

## Description

There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [position_i, speed_i] represents:

• position_i is the distance between the i-th car and the beginning of the road in meters. It is guaranteed that position_i < position_(i+1).
• speed_i is the initial speed of the i-th car in meters per second.

For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.

Return an array answer, where answer[i] is the time, in seconds, at which the i-th car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10^-5 of the actual answers are accepted.

Example 1:

Input: cars = [[1,2],[2,1],[4,3],[7,2]]

Output: [1.00000,-1.00000,3.00000,-1.00000]

Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.

Example 2:

Input: cars = [[3,4],[5,4],[6,3],[9,1]]

Output: [2.00000,1.00000,1.50000,-1.00000]

Constraints:

• 1 <= cars.length <= 10^5
• 1 <= position_i, speed_i <= 10^6
• position_i < position_(i+1)

## Solution

For each car, only the cars before the current car need to be considered. Loop over cars backwards and use monotonic stack, where the bottom element is the lowest car. For each car, if the top element in the stack is slower, then the current car will collide with the car at the top of the stack, and calculate the time that the collision happens.

class Solution {
public double[] getCollisionTimes(int[][] cars) {
int length = cars.length;
double[] times = new double[length];
for (int i = length - 1; i >= 0; i--) {
while (!stack.isEmpty()) {
if (cars[stack.peek()] >= cars[i])
stack.pop();
else {
if (times[stack.peek()] < 0)
break;
double time = times[stack.peek()] * (cars[i] - cars[stack.peek()]);
if (time > cars[stack.peek()] - cars[i])
break;
else
stack.pop();
}
}
if (stack.isEmpty())
times[i] = -1;
else
times[i] = (double) (cars[stack.peek()] - cars[i]) / (cars[i] - cars[stack.peek()]);
stack.push(i);
}
return times;
}
}