04. Last Moment Before All Ants Fall Out of a Plank
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Initialize an integer variable lastFallTime
to 0, which will be used to keep track of the last moment when an ant falls off the plank.
Iterate through the positions of ants moving to the left (from the left
vector):
For each leftPosition
in the left
vector, update lastFallTime
by taking the maximum of its current value and the value of leftPosition
. This represents the farthest position reached by ants moving to the left.
Iterate through the positions of ants moving to the right (from the right
vector):
For each rightPosition
in the right
vector, calculate the farthest position reached by ants moving to the right from the right end of the plank. To do this, subtract rightPosition
from n
(the length of the plank) to get the distance from the right end to the ant's position. Update lastFallTime
by taking the maximum of its current value and this calculated value.
After iterating through both the left and right positions, the lastFallTime
variable will hold the last moment when an ant falls off the plank.
Return the value of lastFallTime
, which represents the last moment at which an ant falls off the plank.
Time Complexity: O(n)
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.