LeetCode-in-Java

3355. Zero Array Transformation I

Medium

You are given an integer array nums of length n and a 2D array queries, where queries[i] = [li, ri].

For each queries[i]:

A Zero Array is an array where all elements are equal to 0.

Return true if it is possible to transform nums into a Zero Array after processing all the queries sequentially, otherwise return false.

A subset of an array is a selection of elements (possibly none) of the array.

Example 1:

Input: nums = [1,0,1], queries = [[0,2]]

Output: true

Explanation:

Example 2:

Input: nums = [4,3,2,1], queries = [[1,3],[0,2]]

Output: false

Explanation:

Constraints:

Solution

public class Solution {
    public boolean isZeroArray(int[] nums, int[][] queries) {
        int n = nums.length;
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum == 0) {
            return true;
        }
        int[] diff = new int[n + 1];
        for (int[] q : queries) {
            int low = q[0];
            int high = q[1];
            diff[low] -= 1;
            if (high + 1 < n) {
                diff[high + 1] += 1;
            }
        }
        for (int i = 0; i < n; i++) {
            if (i > 0) {
                diff[i] += diff[i - 1];
            }
            nums[i] += diff[i];
            sum += diff[i];
            if (nums[i] > 0) {
                return false;
            }
        }
        return sum <= 0;
    }
}