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
:
- Select a subset of indices in the range
[li, ri]
fromnums
. - Decrement the value at each selected index by exactly
vali
.
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.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Example 4
|
|
Constraints
1 <= nums.length <= 10
0 <= nums[i] <= 1000
1 <= queries.length <= 1000
queries[i] = [li, ri, vali]
0 <= li <= ri < nums.length
1 <= vali <= 10
Examples
Solution
Method 1 – Brute Force Simulation
Intuition
Since the array is small (n ≤ 10), we can simulate the process for each prefix of queries. For each k, apply the first k queries in order, always greedily decrementing as much as possible in the allowed range, and check if the array becomes all zeros.
Approach
- For k from 1 to len(queries):
- Copy the original nums array.
- For each query up to k:
- For each index in the range [li, ri]:
- If nums[idx] >= vali, decrement nums[idx] by vali.
- For each index in the range [li, ri]:
- After all k queries, check if all elements are zero.
- If so, return k.
- If no such k exists, return -1.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(q * n^2)
— For each prefix of queries (up to q), we may update up to n elements for each query, and there are up to q queries, so O(q^2 * n) in the worst case, but n is small (≤ 10). - 🧺 Space complexity:
O(n)
— We use a copy of the nums array for each prefix.