Sponsored
Sponsored
The direction change upon collision does not affect the final time an ant falls off. Therefore, the problem simplifies to determining the maximum time taken by any single ant to reach an edge and fall.
Time Complexity: O(m + k), where m and k are the sizes of the 'left' and 'right' arrays respectively.
Space Complexity: O(1), since we are using a constant amount of extra space.
1import java.util.*;
2
3public class Solution {
4 public int getLastMoment(int n, int[] left, int[] right) {
5 int maxTime = 0;
6 for (int position : left) { maxTime = Math.max(maxTime, position); }
7 for (int position : right) { maxTime = Math.max(maxTime, n - position); }
8 return maxTime;
9 }
10 public static void main(String[] args) {
11 Solution solution = new Solution();
12 int[] left = {4, 3};
13 int[] right = {0, 1};
14 int n = 4;
15 int result = solution.getLastMoment(n, left, right);
16 }
17}
This Java solution iterates through each ant's position in the arrays and calculates the maximum time it takes for any ant to fall off the plank.
In this approach, consider the fact that when two ants collide and change directions, it is equivalent to them passing through each other unaffected. Hence, it suffices to only measure how long it takes ants to fall off the plank.
Time Complexity: O(m + k) since we traverse both input arrays once.
Space Complexity: O(1) due to no extra memory required except primitives.
Java's stream
API is used here to compute maximum times for ants on both ends of the plank. It employs a transformation for the 'right' array to capture relevant distances, returning the maximum time.