Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4016e19

Browse files
authored
Create Zero Array Transformation III.py
1 parent 54232be commit 4016e19

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎Zero Array Transformation III.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
You are given an integer array nums of length n and a 2D array queries where queries[i] = [li, ri].
2+
3+
Each queries[i] represents the following action on nums:
4+
5+
Decrement the value at each index in the range [li, ri] in nums by at most 1.
6+
The amount by which the value is decremented can be chosen independently for each index.
7+
A Zero Array is an array with all its elements equal to 0.
8+
9+
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.
10+
----------------------------------------
11+
class Solution:
12+
def maxRemoval(self, nums: List[int], queries: List[List[int]]) -> int:
13+
n, q = len(nums), len(queries)
14+
starts = [[] for _ in range(n)]
15+
for l, r in queries:
16+
starts[l].append(r)
17+
18+
avail = [] # max‐heap of ends (store negatives)
19+
active = [] # min‐heap of ends
20+
chosen = 0
21+
for i in range(n):
22+
for r in starts[i]:
23+
heapq.heappush(avail, -r)
24+
25+
while active and active[0] < i:
26+
heapq.heappop(active)
27+
28+
need = nums[i] - len(active)
29+
for _ in range(need):
30+
while avail and -avail[0] < i:
31+
heapq.heappop(avail)
32+
if not avail:
33+
return -1
34+
r = -heapq.heappop(avail)
35+
heapq.heappush(active, r)
36+
chosen += 1
37+
return q - chosen

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /