Problem Description
Given an integer array nums and a list of queries where each query is represented as [l, r, val], you can subtract from each element in the subarray nums[l]…nums[r] an independently chosen amount up to val. The goal is to determine the minimum number of queries (taking them in sequence) needed such that it becomes possible to reduce every element in nums to 0 (i.e. obtain a Zero Array). If no sequence of queries can achieve this, return -1.
Key Insights
- Each query [l, r, val] offers an independent budget: for every index i in [l, r], you can reduce nums[i] by any amount up to val.
- The total reduction available at an index i after processing some queries is the sum of all val’s from queries that cover index i.
- To be able to zero out nums[i], this sum must be at least nums[i].
- The problem reduces to finding the smallest k (the number of queries from the beginning) such that for every index i, the cumulative available decrement (sum of val’s from the first k queries covering i) is at least nums[i].
- A binary search on the number of queries k is a natural strategy, with a "feasibility check" using a difference array (prefix sum technique) to quickly compute the cumulative decrement available for each index.
Space and Time Complexity
Time Complexity: O((n + Q) * log Q), where n is the length of the nums array and Q is the number of queries.
Space Complexity: O(n), for storing the difference array and cumulative sums.
Solution
We use a binary search over the number of queries k. For each candidate k:
- Build a difference array of length (n+1) and update it for the first k queries. For every query [l, r, val], we add val at diff[l] and subtract val at diff[r+1] (if within bounds).
- Compute the prefix sum on the difference array to obtain the total decrement available at each index.
- Check if for every index the available decrement is at least nums[i]. If yes, candidate k is feasible.
- Return the minimum feasible k found via binary search or -1 if none exists.
This approach leverages the independence of query decrements and the fact that queries are applied in order.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.