Skip to content

Commit 37abffa

Browse files
committed
Time: 3681 ms (18.09%), Space: 17.9 MB (9.04%) - LeetHub
1 parent 151bed0 commit 37abffa

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# time complexity: O(n^2)
2+
# space complexity: O(1)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def countValidSelections(self, nums: List[int]) -> int:
8+
9+
def simulate(start, direction):
10+
n = len(nums)
11+
numsCopy = nums[:]
12+
curr = start
13+
moveRight = direction == 'right'
14+
15+
while 0 <= curr < n:
16+
if numsCopy[curr] == 0:
17+
curr = curr + 1 if moveRight else curr - 1
18+
else:
19+
numsCopy[curr] -= 1
20+
moveRight = not moveRight
21+
curr = curr + 1 if moveRight else curr - 1
22+
return all(x == 0 for x in numsCopy)
23+
24+
n = len(nums)
25+
validCount = 0
26+
27+
for i in range(n):
28+
if nums[i] == 0:
29+
if simulate(i, 'right'):
30+
validCount += 1
31+
if simulate(i, 'left'):
32+
validCount += 1
33+
34+
return validCount
35+
36+
37+
nums1 = [1, 0, 2, 0, 3]
38+
nums2 = [2, 3, 4, 0, 4, 1, 0]
39+
40+
print(Solution().countValidSelections(nums1))
41+
print(Solution().countValidSelections(nums2))

0 commit comments

Comments
 (0)