Apply Operations to Make All Array Elements Equal to Zero - Sweep Line [JS]
Solution: Sweep Line
Keep track of the number of operations for subarrays starting at each index i
.operations[i] = amount to decrease for subarray of size k starting at nums[i]
.
For each subarray operation that we start,
operations[i] -= num
operations[i + k] += num
By keeping the running sum of each operations[i]
, we will get the total amount to decrease each nums[i]
.
If nums[i] + current operations < 0
, then it is impossible.
Time Complexity: O(n)
Space Complexity: O(n)
var checkArray = function(nums, k) {
let n = nums.length, operations = Array(n + 1).fill(0), currOperations = 0;
for (let i = 0; i < n; i++) {
currOperations += operations[i];
let num = nums[i] + currOperations;
if (num < 0) return false;
if (num > 0) {
operations[i] -= num;
if (i + k > n) return false;
operations[i + k] += num;
currOperations -= num;
}
}
return true;
};
Comments
Post a Comment