Greedy + Heap
Intuition\n\nPush all intervals that start before current position and only select at most a[i] intervals to cover current element. To minimize the total number
# Intuition\n\nPush all intervals that start before current position and only select at most `a[i]` intervals to cover current element. To minimize the total number, select intervals with rightmost endpoint. This can be achieved by using a Max-Heap.\n\n# Code\n```cpp []\n#include <bits/stdc++.h>\nusing namespace std;\n\nstruct Comp {\n    bool operator()(const array<int,2>& a, const array<int,2>& b) {\n        return a[1] < b[1];\n    }\n};\n\nclass Solution {\npublic:\n    int maxRemoval(vector<int>& a, vector<vector<int>>& qu) {\n        const int n = a.size();\n        const int m = qu.size();\n        \n        sort(qu.begin(), qu.end(), \n            [](const vector<int>& l, const vector<int>& r) {\n                if (l[0] == r[0]) return l[1] < r[1];\n                return l[0] < r[0];\n        });\n\n        priority_queue<array<int,2>, vector<array<int,2>>, Comp> pq;\n        vector<int> delta(n+1, 0);\n\n        int curr = 0;\n        int needed = 0;\n        int ptr = 0;\n\n        for (int i = 0; i < n; ++i) {\n            curr -= delta[i];\n            while (ptr < m && qu[ptr][0] <= i) {\n                pq.push({qu[ptr][0], qu[ptr][1]});\n                ptr++;\n            }\n            if (pq.size()+curr < a[i]) {return -1;}\n            while (!pq.empty() && curr < a[i]) {\n                const auto t = pq.top();\n                pq.pop();\n                if (t[1] < i) continue;\n                curr++;\n                delta[t[1]+1]++;\n                needed++;\n            }\n\n            if (curr < a[i]) {\n                return -1;\n            }\n\n        }\n\n        return m - needed;\n    }\n};\n```
['C++']