-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathsolution.java
More file actions
50 lines (42 loc) · 1.52 KB
/
Copy pathsolution.java
File metadata and controls
50 lines (42 loc) · 1.52 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
class Solution {
public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) {
int n = positions.length;
Integer[] indices = new Integer[n];
for (int i = 0; i < n; i++) {
indices[i] = i;
}
// Sort indices based on positions
Arrays.sort(indices, (a, b) -> positions[a] - positions[b]);
Stack<Integer> stack = new Stack<>();
for (int idx : indices) {
// Robot moving right
if (directions.charAt(idx) == 'R') {
stack.push(idx);
} else {
// Robot moving left
while (!stack.isEmpty() && healths[idx] > 0) {
int topIdx = stack.peek();
if (healths[topIdx] < healths[idx]) {
stack.pop();
healths[idx]--;
healths[topIdx] = 0;
} else if (healths[topIdx] == healths[idx]) {
stack.pop();
healths[topIdx] = 0;
healths[idx] = 0;
} else {
healths[topIdx]--;
healths[idx] = 0;
}
}
}
}
List<Integer> result = new ArrayList<>();
for (int health : healths) {
if (health > 0) {
result.add(health);
}
}
return result;
}
}