Untitled

 avatar
unknown
plain_text
a year ago
689 B
3
Indexable
class Solution {
public:
    vector<int> asteroidCollision(vector<int>& arr) {
        stack<int>s;
        vector<int>res;
        for(int i=0;i<arr.size();i++){
            if(arr[i]>0 || s.empty()) s.push(arr[i]);
            else{
                while(!s.empty() && s.top()>0 && abs(s.top())< abs(arr[i])) s.pop();

                if(!s.empty() && s.top()>0 && s.top()==abs(arr[i])) s.pop();
                else{
                    if(s.empty() || s.top()<0) s.push(arr[i]);
                }
            }
        }


        while(!s.empty()){
            res.push_back(s.top());
            s.pop();
        }
        reverse(res.begin(),res.end());
        return res;
    }
};
Editor is loading...
Leave a Comment