Simple Priority Queue | Javascript
Intuition\n Describe your first thoughts on how to solve this problem. \nThe earlier approches for iterating through the \'prefix array\' doesn\'t work here.\nI
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe earlier approches for iterating through the \'prefix array\' doesn\'t work here.\nI want to exhaust the nums[i] from the query covering the maximum range. If nums[i] is still > 0, I will exhaust by smaller queries.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- I iterate through all the elements of nums array.\n- Accumulate all the queries covering i such that the query with largest end comes on the top. Use priority queue for the above.\n- Till now I have not started to exhaust the nums[i]\n- On all the queries in priority queue, start exhausting the nums[i] till the pq is empty or the nums[i]+prefix[i] becomes 0.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nLog(n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number}\n */\nvar maxRemoval = function(nums, queries) {\n    queries.sort((a,b)=>a[0]-b[0]);\n    let pq = new MaxPriorityQueue({compare:(a,b)=>b[1]-a[1]});\n    let prefixArray = new Array(nums.length+1).fill(0);\n    let i=0, j=0;\n    \n    while(i<nums.length){\n        if(i>0)\n            prefixArray[i]+=prefixArray[i-1];\n        \n        while(j<queries.length && queries[j][0]<=i){\n            pq.enqueue(queries[j]);\n            j++;\n        }\n        \n        while(!pq.isEmpty() && nums[i]+prefixArray[i]>0 && pq.front()[1]>=i){\n            let [start, end] = pq.dequeue();\n            prefixArray[i]--;\n            prefixArray[end+1]++;\n        }\n        \n        if(nums[i]+prefixArray[i]>0)\n            return -1;\n        i++;\n    }\n    \n    return pq.size();\n};\n```
['JavaScript']