Last Moment Before All Ants Fall Out of a Plank

The problem asks for the maximum time it will take for an ant to reach the end of the plank and fall off, given that when ants meet they will change their direction.

To solve this problem, we can simply return the maximum of three quantities:

  • The maximum position of the ants moving left, because they just need to keep moving left until they fall off.
  • The time it takes for the furthest right moving ant to reach the right end of the plank, which is n - min(right), because they need to move to the right end of the plank.
  • If there are no ants moving in a particular direction, the corresponding quantity will be -inf or +inf. We handle this by checking if the list is empty before calculating these values.

Python solution:

1
2
3
4
5
class Solution:
    def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:
        max_left = max(left) if left else -float('inf')
        min_right = n - min(right) if right else -float('inf')
        return max(max_left, min_right)

This function will return the maximum time it will take for any ant to fall off the plank.