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
- 54 lines of C++ from the credited upstream file 2751.cpp.
- 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.
1struct Robot {2 int index;3 int position;4 int health;5 char direction;6};7 8class Solution {9 public:10 vector<int> survivedRobotsHealths(vector<int>& positions,11 vector<int>& healths, string directions) {12 vector<int> ans;13 vector<Robot> robots;14 vector<Robot> stack; 15 16 for (int i = 0; i < positions.size(); ++i)17 robots.push_back(Robot{i, positions[i], healths[i], directions[i]});18 19 ranges::sort(robots, ranges::less{},20 [](const Robot& robot) { return robot.position; });21 22 for (Robot& robot : robots) {23 if (robot.direction == 'R') {24 stack.push_back(robot);25 continue;26 }27 28 while (!stack.empty() && stack.back().direction == 'R' &&29 robot.health > 0) {30 if (stack.back().health == robot.health) {31 stack.pop_back();32 robot.health = 0;33 } else if (stack.back().health < robot.health) {34 stack.pop_back();35 robot.health -= 1;36 } else { 37 stack.back().health -= 1;38 robot.health = 0;39 }40 }41 if (robot.health > 0)42 stack.push_back(robot);43 }44 45 ranges::sort(stack, ranges::less{},46 [](const Robot& robot) { return robot.index; });47 48 for (const Robot& robot : stack)49 ans.push_back(robot.health);50 51 return ans;52 }53};54