Considre a plank of length n units. Ants are positioned on this plank, and each ant moves at a speed of one unit per second. Some ants move to the left, while others move to the right.
When two ants moving in opposite directions meet at a point, they instantaneously reverse their directions and continue moving. This direction change incurs no additional time cost.
An ant falls off the plank the moment it reaches either end. Given the plank length n and two arrays, left and right, representing the initial positions of ants moving left and right respectively at time t = 0, determine the time at which the last ant falls off the plank.
Example 1:
Input: n = 4, left = [4,3], right = [0,1]
Output: 4
Explanation: Ants are labeled A, B, C, and D. Ant A starts at index 0 moving right. Ant B starts at index 1 moving right. Ant C starts at index 3 moving left. Ant D starts at index 4 moving left. The last ant falls off the plank at t = 4 seconds.
Example 2:
Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
Output: 7
Explanation: All ants move right. The ant starting at index 0 takes 7 seconds to fall off.
Example 3:
Input: n = 7, left = [0,1,2,3,4,5,6,7], right = []
Output: 7
Explanation: All ants move left. The ant starting at index 7 takes 7 seconds to fall off.
Example 4:
Input: n = 9, left = [5], right = [4]
Output: 5
Explanation: At t = 1 second, the two ants effectively swap starting positions and continue in their original directions.
Example 5:
Input: n = 6, left = [6], right = [0]
Output: 6
Constraints:
1 <= n <= 10^40 <= left.length <= n + 10 <= left[i] <= n0 <= right.length <= n + 10 <= right[i] <= n1 <= left.length + right.length <= n + 1- All values in
leftandrightare unique and appear in only one of the arrays.
class Solution {
public int getLastMoment(int n, int[] left, int[] right) {
int maxTime = 0;
for (int pos : left) {
maxTime = Math.max(maxTime, pos);
}
for (int pos : right) {
maxTime = Math.max(maxTime, n - pos);
}
return maxTime;
}
}