-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsteroid Collision.cpp
More file actions
108 lines (100 loc) · 3.38 KB
/
Asteroid Collision.cpp
File metadata and controls
108 lines (100 loc) · 3.38 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*My approach is to use <strong> stack </strong>
there are certain cases we need to take care of :-
1. if element is positive we push in stack.
2. if stack is empty we push whatever element we have (negative or positive )
3. if stack top element is -ve we push the current element
4. if stack top element is positive we pop it out of stack until we find any element whose value is greater than or equal to abs( current element )
5. if stack becomes empty after performing operation 4 we will push the current element in stack
6. now we will take all the elements from stack and push it in vector and reverse it as stack uses LIFO( last in first out)
*/
#include<bits/stdc++.h>
using namespace std;
vector<int> asteroidCollision(vector<int>& asteroids) {
stack<int>P;
for(auto x:asteroids)
{
if(x>0)
{
P.push(x);
}
else
{
if(!P.empty())
{
int temp=P.top();
if(temp<0)
{
P.push(x);
}
else
{
if(temp<=abs(x))
{
while(1)
{
int y=P.top();
if(y<0)
{
P.push(x);
break;
}
else
{
if(y==abs(x))
{
P.pop();
break;
}
else
{
if(y>abs(x))
{
break;
}
else
{
P.pop();
}
}
}
if(P.empty())
{
P.push(x);
break;
}
}
}
}
}
else
{
P.push(x);
}
}
}
vector<int>ans;
while(!P.empty())
{
ans.push_back(P.top());
P.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
int main()
{
int n;
cin>>n;
vector<int>asteroids(n);
for(int i=0;i<n;++i)
{
cin>>asteroids[i];
}
vector<int> ans = asteroidCollision( asteroids);
cout<<"[ ";
for( auto x: ans)
{
cout<< x<<", ";
}
cout<<"]";
}