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.
1#include <stdio.h>
2
3int getLastMoment(int n, int* left, int leftSize, int* right, int rightSize) {
4 int maxTime = 0;
5 for (int i = 0; i < leftSize; i++) {
6 if (left[i] > maxTime) maxTime = left[i];
7 }
8 for (int i = 0; i < rightSize; i++) {
9 if (n - right[i] > maxTime) maxTime = n - right[i];
10 }
11 return maxTime;
12}
13
14int main() {
15 int n = 4;
16 int left[] = {4, 3};
17 int right[] = {0, 1};
18 int result = getLastMoment(n, left, 2, right, 2);
19 printf("%d\n", result);
20 return 0;
21}
This solution loops through both the 'left' and 'right' arrays, calculating the maximum time required for both left-moving and right-moving ants to fall off. It calculates the time for left ants to reach position 0 and for right ants to reach position n, updating the maximum.
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.