1776. Car Fleet II

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1776

class Solution:
    def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:
        stk = []
        n = len(cars)
        res = [-1] * n
        for i in range(n - 1, -1, -1):
            while stk:
                j = stk[-1]
                if cars[i][1] > cars[j][1]:
                    t = (cars[j][0] - cars[i][0]) / (cars[i][1] - cars[j][1])
                    if res[j] == -1 or t <= res[j]:
                        res[i] = t
                        break
                stk.pop()
            stk.append(i)
        return res