[LeetCode] Movement of Robots

2731. Movement of Robots

Some robots are standing on an infinite number line with their initial coordinates given by a 0-indexed integer array nums and will start moving once given the command to move. The robots will move a unit distance each second.

You are given a string s denoting the direction in which robots will move on command. 'L' means the robot will move towards the left side or negative side of the number line, whereas 'R' means the robot will move towards the right side or positive side of the number line.

If two robots collide, they will start moving in opposite directions.

Return the sum of distances between all the pairs of robots d seconds after the command. Since the sum can be very large, return it modulo 109 + 7.

Note:

  • For two robots at the index i and j, pair (i,j) and pair (j,i) are considered the same pair.
  • When robots collide, they instantly change their directions without wasting any time.
  • Collision happens when two robots share the same place in a moment.
    • For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they’ll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.
    • For example, if a robot is positioned in 0 going to the right and another is positioned in 1 going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int sumDistance(vector<int>& nums, string s, int d) {
vector<long long> A;
for(int i = 0; i < nums.size(); i++) {
long long x = nums[i];
if(s[i] == 'L') x -= d;
else x += d;
A.push_back(x);
}
sort(begin(A), end(A));
for(int i = A.size() - 1; i >= 0; i--) A[i] -= A[0];
long long sum = 0, res = 0, mod = 1e9 + 7;
for(int i = 0; i < A.size(); i++) {
res = (res + A[i] * i % mod - sum + mod) % mod;
sum = (sum + A[i]) % mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/11/PS/LeetCode/movement-of-robots/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.