Apply Operations to Make All Array Elements Equal to Zero Problem
Description
LeetCode Problem 2772.
You are given a 0-indexed integer array nums and a positive integer k.
You can apply the following operation on the array any number of times:
- Choose any subarray of size
kfrom the array and decrease all its elements by1.
Return true if you can make all the array elements equal to 0, or false otherwise.
A subarray is a contiguous non-empty part of an array.
Example 1:
Input: nums = [2,2,3,1,1,0], k = 3
Output: true
Explanation: We can do the following operations:
- Choose the subarray [2,2,3]. The resulting array will be nums = [1,1,2,1,1,0].
- Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,1,0,0,0].
- Choose the subarray [1,1,1]. The resulting array will be nums = [0,0,0,0,0,0].
Example 2:
Input: nums = [1,3,1,1], k = 2
Output: false
Explanation: It is not possible to make all the array elements equal to 0.
Constraints:
1 <= k <= nums.length <= 10^50 <= nums[i] <= 10^6
Solution
Approach: Greedy with a Difference Array
Go left to right. The first element can only be reduced by operations starting at index 0, so if it is v > 0 we must apply exactly v operations on nums[0..k-1]. Repeat the same reasoning for each later element.
To apply "subtract v from a window" cheaply, keep a running sum s of pending subtractions and a difference array d that records where each one stops:
- At index
i, addd[i]tosand addstonums[i](as a running valuex). - If
x == 0, continue. - If
x < 0, or the window does not fit (i + k > n), returnfalse. - Otherwise subtract
xfromsand addxtod[i + k], since the window ends beforei + k.
If the loop finishes, return true.
Complexity: O(n) time and O(n) space.
class Solution:
def checkArray(self, nums: List[int], k: int) -> bool:
n = len(nums)
d = [0] * (n + 1)
s = 0
for i, x in enumerate(nums):
s += d[i]
x += s
if x == 0:
continue
if x < 0 or i + k > n:
return False
s -= x
d[i + k] += x
return True