[LeetCode] Make Array Elements Equal to Zero

3354. Make Array Elements Equal to Zero

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:

  • If curr is out of the range [0, n - 1], this process ends.

  • If nums[curr] == 0, move in the current direction by incrementing curr if you are moving right, or decrementing curr if you are moving left.

  • Else if nums[curr] > 0:

    • Decrement nums[curr] by 1.
    • Reverse your movement direction (left becomes right and vice versa).
    • Take a step in your new direction.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int countValidSelections(vector<int>& nums) {
int ri = accumulate(begin(nums), end(nums), 0), le = 0, res = 0;
for(int i = 0; i < nums.size(); i++) {
if(!nums[i]) {
if(le == ri) res += 2;
else if(abs(le-ri) == 1) res += 1;
}
le += nums[i], ri -= nums[i];
if(le > ri + 1) return res;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/17/PS/LeetCode/make-array-elements-equal-to-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.