1+ /**
2+ * 3354. Make Array Elements Equal to Zero
3+ *
4+ * curr = index,nums[index] == 0
5+ * 若curr超過範圍[0,nums.length - 1] 操作結束
6+ * 若nums[index] == 0,則curr 增加(往右),反之則curr減少(往左)
7+ * nums[index] > 0 ,nums[current] - 1且左右反轉
8+ *
9+ * @param {number[] } nums
10+ * @return {number }
11+ */
12+ var countValidSelections = function ( nums ) {
13+ // you need to find the sum of all the numbers to the left of where nums[i]==0 and the sum of all the numbers to the right of that point.
14+ // If you need more help, look at the detailed explanation in this comment.
15+ let ans = 0 ;
16+ let sum = nums . reduce ( ( a , b ) => a + b , 0 ) ;
17+ let left = 0 , right = sum ;
18+ for ( let i = 0 ; i < nums . length ; ++ i ) {
19+ if ( nums [ i ] === 0 ) {
20+ if ( left - right >= 0 && left - right <= 1 ) {
21+ ans ++ ;
22+ }
23+ if ( right - left >= 0 && right - left <= 1 ) {
24+ ans ++ ;
25+ }
26+ } else {
27+ left += nums [ i ] ;
28+ right -= nums [ i ] ;
29+ }
30+ }
31+ return ans ;
32+ } ;
33+ let nums = [ 1 , 0 , 2 , 0 , 3 ] ;
34+ /**
35+ * 2
36+ * The only possible valid selections are the following:
37+ Choose curr = 3, and a movement direction to the left.
38+ [1,0,2,0,3] -> [1,0,2,0,3] -> [1,0,1,0,3] -> [1,0,1,0,3] -> [1,0,1,0,2] ->
39+ [1,0,1,0,2] -> [1,0,0,0,2] -> [1,0,0,0,2] -> [1,0,0,0,1] -> [1,0,0,0,1] ->
40+ [1,0,0,0,1] -> [1,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] ->
41+ [0,0,0,0,1] -> [0,0,0,0,0].
42+
43+ Choose curr = 3, and a movement direction to the right.
44+ [1,0,2,0,3] -> [1,0,2,0,3] -> [1,0,2,0,2] -> [1,0,2,0,2] -> [1,0,1,0,2] ->
45+ [1,0,1,0,2] -> [1,0,1,0,1] -> [1,0,1,0,1] -> [1,0,0,0,1] -> [1,0,0,0,1] ->
46+ [1,0,0,0,0] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [0,0,0,0,0].
47+ */
48+ console . log ( countValidSelections ( nums ) ) ;
0 commit comments