Zero Array Transformation II - Problem
You are given an integer array nums of length n and a 2D array queries where queries[i] = [li, ri, vali].
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 vali. The amount by which each 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 minimum possible non-negative value of k, such that after processing the first k queries in sequence, nums becomes a Zero Array. If no such k exists, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,3], queries = [[0,2,1],[1,2,1]]
›
Output:
2
💡 Note:
With k=2 queries: first query decrements range [0,2] by up to 1 each, second query decrements range [1,2] by up to 1 each. Total possible decrements: [1,2,2], which covers nums=[2,1,3]
Example 2 — Impossible Case
$
Input:
nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]
›
Output:
-1
💡 Note:
Even with all queries, max decrements are [1,3,3,2]. Position 0 needs 4 decrements but only gets 1, so impossible
Example 3 — Already Zero
$
Input:
nums = [0,0,0], queries = [[0,2,1]]
›
Output:
0
💡 Note:
Array is already all zeros, so k=0 queries needed
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 106
- 1 ≤ queries.length ≤ 105
- queries[i].length = 3
- 0 ≤ li ≤ ri < nums.length
- 1 ≤ vali ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums and queries with [left, right, value] ranges
2
Process
Apply first k queries to get total possible decrements
3
Check
Verify if decrements ≥ original values for all positions
Key Takeaway
🎯 Key Insight: Binary search on k combined with difference arrays for O(n log m) efficiency
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code