Leetcode #1503: Last Moment Before All Ants Fall Out of a Plank

Link to the Problem

Last Moment Before All Ants Fall Out of a Plank

Thought Process

The problem is a lot about observation. Observing and analyzing the ant behavior will reveal that the problem is way too tricky to understand but way too easy to implement. The idea is to think of the bigger picture and focus only on the paths of the ants. At any collision, think of it as ants transferring their responsibility of going to the other end, to each other. So one ant covers the path for the other.

Leetcode #1503: Last Moment Before All Ants Fall Out of a Plank - Diagram to assist visualization, Problem Solving, Leetcode, Leetcode Solutions, Crack Coding Interview, Coding Interview, Data Structures and Algorithms
Leetcode #1503: Last Moment Before All Ants Fall Out of a Plank – Diagram to assist visualization

(If the above image look too small, click on it.)

Algorithm

  1. Find the distance of the ant going in the left direction which is farthest from the left end of the plank.
  2. Find the distance of the ant going in the right direction which is farthest from the right end of the plank.
  3. Max of the above two is the answer.

Code

class Solution {
public:
int getLastMoment(int n, vector<int>& left, vector<int>& right) {
// The one that is farthest from the left end, but desires to go in the left
// direction, will be the last one to go off of the plank from the left side.
int maxLeft = left.empty() ? 0 : *max_element(left.begin(), left.end());
// Similarly,
// The one that is farthest from the right end, but desires to go in the right
// direction, will be the last one to go off of the plank from the right side.
int minRight = right.empty() ? n : *min_element(right.begin(), right.end());
// The one among above two would be the last one to off of the plank among all.
return max(maxLeft, n - minRight);
}
};
view raw Leetcode_1503.cpp hosted with ❤ by GitHub

Is there anything that is still unclear? Let me know in the comments and I can elaborate further.

Don’t forget like & share the post, and subscribe to the blog to get notifications whenever solution to a new problem is added.

Happy Coding!

Similar Problems

Leetcode #121: Best Time to Buy and Sell Stock



Related Posts


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s