-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathsolution.cpp
More file actions
72 lines (65 loc) · 2.05 KB
/
Copy pathsolution.cpp
File metadata and controls
72 lines (65 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution
{
public:
vector<int> survivedRobotsHealths(vector<int> &positions, vector<int> &healths, string directions)
{
int n = positions.size();
// Store robot indices
vector<int> indices(n);
for (int i = 0; i < n; i++)
{
indices[i] = i;
}
// Sort indices based on robot positions
sort(indices.begin(), indices.end(), [&](int a, int b)
{ return positions[a] < positions[b]; });
// Stack to keep indices of robots moving right
stack<int> st;
for (int idx : indices)
{
// If robot moves right, push it into stack
if (directions[idx] == 'R')
{
st.push(idx);
}
else
{
// Current robot is moving left
while (!st.empty() && healths[idx] > 0)
{
int topIdx = st.top();
// Right robot has smaller health
if (healths[topIdx] < healths[idx])
{
st.pop();
healths[idx]--;
healths[topIdx] = 0;
}
// Both have same health
else if (healths[topIdx] == healths[idx])
{
st.pop();
healths[topIdx] = 0;
healths[idx] = 0;
}
// Left robot has smaller health
else
{
healths[topIdx]--;
healths[idx] = 0;
}
}
}
}
// Collect surviving robots in original order
vector<int> result;
for (int i = 0; i < n; i++)
{
if (healths[i] > 0)
{
result.push_back(healths[i]);
}
}
return result;
}
};