[LeetCode] Apply Operations to Make All Array Elements Equal to Zero

2772. Apply Operations to Make All Array Elements Equal to Zero

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 k from the array and decrease all its elements by 1.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool checkArray(vector<int>& nums, int k) {
vector<int> pre(nums.size() + 1);
for(int i = 0; i < nums.size() - k + 1; i++) {
if(i) pre[i] += pre[i-1];
nums[i] -= pre[i];
if(nums[i] < 0) return false;
pre[i] += nums[i];
pre[i+k] -= nums[i];
}
for(int i = nums.size() - k + 1; i < nums.size(); i++) {
if(i) pre[i] += pre[i-1];
nums[i] -= pre[i];
if(nums[i] != 0) return false;
}
return true;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/09/PS/LeetCode/apply-operations-to-make-all-array-elements-equal-to-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.