04. Last Moment Before All Ants Fall Out of a Plank
The problem can be found at the following link: Question Link
My Approach
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 theleft
vector, updatelastFallTime
by taking the maximum of its current value and the value ofleftPosition
. 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 theright
vector, calculate the farthest position reached by ants moving to the right from the right end of the plank. To do this, subtractrightPosition
fromn
(the length of the plank) to get the distance from the right end to the ant's position. UpdatelastFallTime
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 and Auxiliary Space Complexity
Time Complexity:
O(n)
Auxiliary Space Complexity:
O(1)
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 rishabhv12/Daily-Leetcode-Solution repository.
Last updated