Zero Array Transformation IV - Problem
You are given an integer array nums of length n and a 2D array queries, where queries[i] = [l_i, r_i, val_i].
Each queries[i] represents the following action on nums:
- Select a subset of indices in the range
[l_i, r_i]fromnums. - Decrement the value at each selected index by exactly
val_i.
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],[1,1,3]]
›
Output:
2
💡 Note:
After applying first 2 queries: query [0,2,1] reduces range [0,2] by 1, query [1,2,1] reduces range [1,2] by 1. Total reductions: [1,2,2] which can make [2,1,3] → [0,0,0]
Example 2 — Impossible Case
$
Input:
nums = [5,2,4], queries = [[0,1,1],[1,2,1]]
›
Output:
-1
💡 Note:
Even using all queries, maximum reductions are [1,2,1] which cannot reduce [5,2,4] to zero since 1 < 5
Example 3 — Zero Queries Needed
$
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] ≤ 109
- 1 ≤ queries.length ≤ 105
- queries[i].length = 3
- 0 ≤ li ≤ ri < nums.length
- 1 ≤ vali ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,1,3] and queries [[0,2,1],[1,2,1],[1,1,3]]
2
Process
Find minimum k queries to make array all zeros
3
Output
Return k=2 (first 2 queries sufficient)
Key Takeaway
🎯 Key Insight: Binary search on k combined with difference arrays for efficient feasibility checking
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code