LC 3362. 零数组变换 III
https://leetcode.cn/problems/zero-array-transformation-iii/description/
这题看了题解,的确是很好的解决办法,大致思路就是:
- 需要维护一个差分数组,用来计算如果选择了某个范围之后的情况。
- 遍历 `nums` 的时候,需要不断地将可用的范围加入到 `h` 这个heap里面。
- 然后再挑选范围的时候,每次都只挑选最远ending point的范围, 从heap里面移除
class Solution: def maxRemoval(self, nums: List[int], queries: List[List[int]]) -> int: n = len(nums) queries.sort() diff = [0] * (n + 1) h = [] sum_d, j = 0, 0 for i, x in enumerate(nums): sum_d += diff[i] # add query end into heap while j < len(queries) and queries[j][0] <= i: heapq.heappush(h, -queries[j][1]) j += 1 while sum_d < x and h and -h[0] >= i: diff[-h[0] + 1] -= 1 sum_d += 1 heapq.heappop(h) if sum_d < x: return -1 return len(h)