Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active March 13, 2025 20:09
Show Gist options
  • Save tatsuyax25/222108f68602ac9d09a86dd7b8e48a9d to your computer and use it in GitHub Desktop.
Save tatsuyax25/222108f68602ac9d09a86dd7b8e48a9d to your computer and use it in GitHub Desktop.
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
/**
* Checks if the array can be made zero with a given number of queries.
* @param {number[]} nums - The array of numbers.
* @param {number[][]} queries - The array of queries.
* @param {number} limit - The number of queries to use.
* @return {boolean} - Returns true if the array can be made zero, false otherwise.
*/
let check = (nums, queries, limit) => {
let arr = new Array(nums.length + 1).fill(0);
// Apply each query to the arr array
for (let i = 0; i < limit; i++) {
arr[queries[i][0]] -= queries[i][2];
arr[queries[i][1] + 1] += queries[i][2];
}
let dec = 0;
let sum = 0;
// Calculate the decayed values and sum up if they are positive
for (let i = 0; i < nums.length; i++) {
dec += arr[i];
if (nums[i] + dec > 0) {
sum += nums[i];
}
}
// Return true if sum of positive elements is zero
return sum == 0;
};
/**
* Finds the minimum number of queries needed to make the array sum zero.
* @param {number[]} nums - The array of numbers.
* @param {number[][]} queries - The array of queries.
* @return {number} - The minimum number of queries needed, or -1 if not possible.
*/
var minZeroArray = function(nums, queries) {
let sum = 0;
// Calculate the initial sum of the array
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
}
// If the sum is already zero, no queries are needed
if (sum == 0) {
return 0;
}
let n = nums.length;
let l = 1, r = queries.length;
let res = -1;
// Binary search to find the minimum number of queries needed
while (l <= r) {
let mid = Math.floor((l + r) / 2);
if (check(nums, queries, mid)) {
res = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return res;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment