Approach
Sorting and greedy selection
For Robot Collisions, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 55 lines of Java from the credited upstream file 2751.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Robot {2 public int index;3 public int position;4 public int health;5 public char direction;6 public Robot(int index, int position, int health, char direction) {7 this.index = index;8 this.position = position;9 this.health = health;10 this.direction = direction;11 }12}13 14class Solution {15 public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {16 List<Integer> ans = new ArrayList<>();17 Robot[] robots = new Robot[positions.length];18 List<Robot> stack = new ArrayList<>(); 19 20 for (int i = 0; i < positions.length; ++i)21 robots[i] = new Robot(i, positions[i], healths[i], directions.charAt(i));22 23 Arrays.sort(robots, Comparator.comparingInt((Robot robot) -> robot.position));24 25 for (Robot robot : robots) {26 if (robot.direction == 'R') {27 stack.add(robot);28 continue;29 }30 31 while (!stack.isEmpty() && stack.get(stack.size() - 1).direction == 'R' && robot.health > 0) {32 if (stack.get(stack.size() - 1).health == robot.health) {33 stack.remove(stack.size() - 1);34 robot.health = 0;35 } else if (stack.get(stack.size() - 1).health < robot.health) {36 stack.remove(stack.size() - 1);37 robot.health -= 1;38 } else { 39 stack.get(stack.size() - 1).health -= 1;40 robot.health = 0;41 }42 }43 if (robot.health > 0)44 stack.add(robot);45 }46 47 stack.sort(Comparator.comparingInt((Robot robot) -> robot.index));48 49 for (Robot robot : stack)50 ans.add(robot.health);51 52 return ans;53 }54}55