Skip to content

Commit 1865623

Browse files
committed
Added solution for N-Robots-Collisions problem
1 parent 7b1995f commit 1865623

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.thealgorithms.simulation;
2+
3+
public class NRobotsCollision {
4+
static class Pair {
5+
int first;
6+
char second;
7+
Pair(int first, char second) {
8+
this.first = first;
9+
this.second = second;
10+
}
11+
}
12+
public static int earliestCollisionTime(int n, int[] positions, String directions) {
13+
List<Pair> sortedDirections = new ArrayList<>();
14+
for(int i = 0; i < n; i++){
15+
sortedDirections.add(new Pair(positions[i], directions.charAt(i)));
16+
}
17+
sortedDirections.sort((a, b) -> Integer.compare(a.first, b.first));
18+
int minTime = Integer.MAX_VALUE;
19+
for(int i = 1; i < n; i++){
20+
if(sortedDirections.get(i).second == 'L' && sortedDirections.get(i - 1).second == 'R'){
21+
minTime = Math.min(minTime, sortedDirections.get(i).first - sortedDirections.get(i - 1).first);
22+
}
23+
}
24+
return minTime == Integer.MAX_VALUE ? -1 : minTime / 2;
25+
}
26+
}

0 commit comments

Comments
 (0)