Apply Operations to Make All Array Elements Equal to Zero - Sweep Line [JS]

Description 

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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]