LeetCode-in-Java

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

Medium

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:

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:

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:

Solution

public class Solution {
    public boolean checkArray(int[] nums, int k) {
        int cur = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if (cur > nums[i]) {
                return false;
            }
            nums[i] -= cur;
            cur += nums[i];
            if (i >= k - 1) {
                cur -= nums[i - k + 1];
            }
        }
        return cur == 0;
    }
}