|
| 1 | +/** |
| 2 | + * 3354. Make Array Elements Equal to Zero |
| 3 | + * https://leetcode.com/problems/make-array-elements-equal-to-zero/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * You are given an integer array nums. |
| 7 | + * |
| 8 | + * Start by selecting a starting position curr such that nums[curr] == 0, and choose a movement |
| 9 | + * direction of either left or right. |
| 10 | + * |
| 11 | + * After that, you repeat the following process: |
| 12 | + * - If curr is out of the range [0, n - 1], this process ends. |
| 13 | + * - If nums[curr] == 0, move in the current direction by incrementing curr if you are moving |
| 14 | + * right, or decrementing curr if you are moving left. |
| 15 | + * - Else if nums[curr] > 0: |
| 16 | + * - Decrement nums[curr] by 1. |
| 17 | + * - Reverse your movement direction (left becomes right and vice versa). |
| 18 | + * - Take a step in your new direction. |
| 19 | + * |
| 20 | + * A selection of the initial position curr and movement direction is considered valid if |
| 21 | + * every element in nums becomes 0 by the end of the process. |
| 22 | + * |
| 23 | + * Return the number of possible valid selections. |
| 24 | + */ |
| 25 | + |
| 26 | +/** |
| 27 | + * @param {number[]} nums |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var countValidSelections = function(nums) { |
| 31 | + const n = nums.length; |
| 32 | + let result = 0; |
| 33 | + |
| 34 | + for (let i = 0; i < n; i++) { |
| 35 | + if (nums[i] === 0) { |
| 36 | + if (helper(i, -1)) result++; |
| 37 | + if (helper(i, 1)) result++; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | + |
| 43 | + function helper(startIndex, direction) { |
| 44 | + const arr = [...nums]; |
| 45 | + let current = startIndex; |
| 46 | + let dir = direction; |
| 47 | + |
| 48 | + while (current >= 0 && current < n) { |
| 49 | + if (arr[current] === 0) { |
| 50 | + current += dir; |
| 51 | + } else { |
| 52 | + arr[current]--; |
| 53 | + dir = -dir; |
| 54 | + current += dir; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return arr.every(val => val === 0); |
| 59 | + } |
| 60 | +}; |
0 commit comments