Leetcode: 1776. Car Fleet II

Problem Statement

from typing import List


class Solution:
    def getCollisionTimes(self, c: List[List[int]]) -> List[float]:
        def t(a, b):
            return (b[0] - a[0]) / (a[1] - b[1])

        N = len(c)
        ans = [-1] * N
        st = []
        for i in range(N - 1, -1, -1):
            while st and (
                st[-1][1] >= c[i][1] or 0 < ans[st[-1][2]] <= t(c[i], st[-1])
            ):
                st.pop()
            if st:
                ans[i] = t(c[i], st[-1])
            st.append((*c[i], i))
        return ans


assert Solution().getCollisionTimes([[1, 2], [2, 1], [4, 3], [7, 2]]) == [
    1.00000,
    -1.00000,
    3.00000,
    -1.00000,
]
assert Solution().getCollisionTimes([[3, 4], [5, 4], [6, 3], [9, 1]]) == [
    2.00000,
    1.00000,
    1.50000,
    -1.00000,
]