LeetCode-in-Java

3354. Make Array Elements Equal to Zero

Easy

You are given an integer array nums.

Start by selecting a starting position curr such that nums[curr] == 0, and choose a movement direction of either left or right.

After that, you repeat the following process:

A selection of the initial position curr and movement direction is considered valid if every element in nums becomes 0 by the end of the process.

Return the number of possible valid selections.

Example 1:

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

Output: 2

Explanation:

The only possible valid selections are the following:

Example 2:

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

Output: 0

Explanation:

There are no possible valid selections.

Constraints:

Solution

public class Solution {
    public int countValidSelections(int[] nums) {
        int[] rightSum = new int[nums.length];
        int[] leftSum = new int[nums.length];
        int result = 0;
        leftSum[0] = 0;
        rightSum[nums.length - 1] = 0;
        for (int i = 1; i < nums.length; i++) {
            leftSum[i] = leftSum[i - 1] + nums[i - 1];
        }
        for (int j = nums.length - 2; j >= 0; j--) {
            rightSum[j] = rightSum[j + 1] + nums[j + 1];
        }
        for (int k = 0; k < nums.length; k++) {
            if (nums[k] == 0 && Math.abs(rightSum[k] - leftSum[k]) == 1) {
                result++;
            }
            if (nums[k] == 0 && Math.abs(rightSum[k] - leftSum[k]) == 0) {
                result += 2;
            }
        }
        return result;
    }
}