-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroid Collision.java
More file actions
61 lines (50 loc) · 1.52 KB
/
Copy pathAsteroid Collision.java
File metadata and controls
61 lines (50 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
51
52
53
54
55
56
57
58
59
60
61
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int N;
N = sc.nextInt();
int[] asteroids = new int[N];
for (int i = 0; i < N; i++) asteroids[i] = sc.nextInt();
Solution obj = new Solution();
int[] res = obj.asteroidCollision(N, asteroids);
for (int e : res) System.out.print(e + " ");
System.out.println();
}
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
public static int[] asteroidCollision(int N, int[] arr) {
// code here
Stack<Integer> st=new Stack<>();
for(int num:arr){
if(num<0){
while(!st.isEmpty() && st.peek()>0 && st.peek()<Math.abs(num)){
st.pop();
}
if(!st.isEmpty()){
if(st.peek()==Math.abs(num)){
st.pop();
}else if(st.peek()<0){
st.push(num);
}
}else if(st.isEmpty()){
st.push(num);
}
}else{
st.push(num);
}
}
int[] ans =new int[st.size()];
int i=st.size()-1;
while(st.size()>0)ans[i--]=st.pop();
return ans;
}
}