File tree Expand file tree Collapse file tree
src/main/java/com/thealgorithms/simulation Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments