Last Object Exit Time
Problem statement
Several objects move along a table represented by the line segment from 0 to tableLength. For object i, position[i] is its distinct starting coordinate and velocity[i] is its nonzero signed velocity.
- A positive velocity moves an object to the right.
- A negative velocity moves an object to the left.
- All objects start moving simultaneously at time
0. - When two objects collide, they instantly exchange velocities.
- An object leaves the table after crossing either boundary.
Return the ceiling of the time when the final object leaves the table.
Function
lastObjectExitTime(tableLength: int, position: int[], velocity: int[]) → intExamples
Example 1
tableLength = 9position = [2,4,5]velocity = [2,-2,4]return = 4Because equal-mass collisions exchange velocities, the set of paths is equivalent to the objects passing through one another. Their independent exit times are 7/2, 4/2, and 4/4 seconds. The maximum is 3.5, whose ceiling is 4.
Constraints
tableLength > 0.position.length == velocity.lengthand at least one object is present.- Every
position[i]is strictly between0andtableLength. - No two objects have the same starting position.
- Every
velocity[i]is nonzero. - Collisions occur instantly.