-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
37 lines (31 loc) · 899 Bytes
/
Copy pathsolution.cpp
File metadata and controls
37 lines (31 loc) · 899 Bytes
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
class Solution
{
public:
vector<int> makeBeautiful(vector<int> arr)
{
// This vector will work like a stack
vector<int> st;
// Traverse every element of the array
for (int num : arr)
{
// Check if stack is not empty
// and current number has opposite sign
// compared to the top element
if (!st.empty() &&
((st.back() >= 0 && num < 0) ||
(st.back() < 0 && num >= 0)))
{
// Remove the previous element
// because both cancel each other
st.pop_back();
}
else
{
// Otherwise keep the current element
st.push_back(num);
}
}
// Final beautiful array
return st;
}
};