#3362
Zero Array Transformation III
MediumArrayTwo PointersGreedySortingHeap (Priority Queue)Prefix SumGreedyPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Sort the queries and use a greedy approach to maximize the number of removable queries while ensuring the remaining can still zero out the array.
⚙️
Algorithm
3 steps- 1Step 1: Sort queries based on their end index.
- 2Step 2: Use a prefix sum to track the total decrements needed for each index.
- 3Step 3: Iterate through queries, checking if removing the last query still allows nums to be zeroed out.
solution.py15 lines
1def maxRemovable(nums, queries):
2 queries.sort(key=lambda x: x[1])
3 total_decrements = [0] * (len(nums) + 1)
4 for l, r in queries:
5 total_decrements[l] += 1
6 if r + 1 < len(total_decrements):
7 total_decrements[r + 1] -= 1
8 for i in range(1, len(total_decrements)):
9 total_decrements[i] += total_decrements[i - 1]
10 max_removable = 0
11 for i in range(len(nums)):
12 if total_decrements[i] > nums[i]:
13 return -1
14 max_removable += total_decrements[i]
15 return len(queries) - max_removableℹ
Complexity note: The sorting step dominates the complexity, making it efficient compared to brute force.
- 1Greedy approach maximizes efficiency.
- 2Sorting helps in managing overlapping ranges.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.