[LeetCode] Zero Array Transformation III

3362. Zero Array Transformation III

You are given an integer array nums of length n and a 2D array queries where queries[i] = [li, ri].

Each queries[i] represents the following action on nums:

  • Decrement the value at each index in the range [li, ri] in nums by at most 1.
  • The amount by which the value is decremented can be chosen independently for each index.

A Zero Array is an array with all its elements equal to 0.

Return the maximum number of elements that can be removed from queries, such that nums can still be converted to a zero array using the remaining queries. If it is not possible to convert nums to a zero array, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int maxRemoval(vector<int>& nums, vector<vector<int>>& queries) {
int res = queries.size();
vector<int> pre(nums.size() + 1);
sort(rbegin(queries), rend(queries));
priority_queue<int> q;
for(int i = 0; i < nums.size(); i++) {
while(queries.size() and queries.back()[0] <= i) {
q.push(queries.back()[1]);
queries.pop_back();
}
if(i) pre[i] += pre[i-1];
while(nums[i] > pre[i]) {
if(q.size() == 0 or q.top() < i) return -1;
pre[i]++;
pre[q.top() + 1]--;
res--;
q.pop();
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/24/PS/LeetCode/zero-array-transformation-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.