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.
1using System;
2
3public class Solution {
4 public int GetLastMoment(int n, int[] left, int[] right) {
5 int maxTime = 0;
6 foreach (int pos in left) { maxTime = Math.Max(maxTime, pos); }
7 foreach (int pos in right) { maxTime = Math.Max(maxTime, n - pos); }
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 C# solution loops through the arrays and finds the last moment an ant will fall off by capturing the maximum time among all ants on both sides.
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.
1using System.Linq;
public class Solution {
public int GetLastMoment(int n, int[] left, int[] right) {
int maxTimeLeft = left.Length > 0 ? left.Max() : 0;
int maxTimeRight = right.Length > 0 ? right.Select(x => n - x).Max() : 0;
return Math.Max(maxTimeLeft, maxTimeRight);
}
public static void Main(string[] args) {
int[] left = {4, 3};
int[] right = {0, 1};
int n = 4;
Solution solution = new Solution();
int result = solution.GetLastMoment(n, left, right);
}
}
C# utilizes Max
and Select
extensions from LINQ to accomplish the task efficiently through functional expressions. It maintains checks for potential empty lists.