-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmake-array-elements-equal-to-zero.py
36 lines (33 loc) · 1.08 KB
/
make-array-elements-equal-to-zero.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Time: O(n)
# Space: O(1)
# prefix sum, CodeChef Starters 146 - Bouncing Ball (https://www.codechef.com/problems/BOUNCE_BALL)
class Solution(object):
def countValidSelections(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total = sum(nums)
result = curr = 0
for x in nums:
if not x:
result += max(2-abs(curr-(total-curr)), 0)
else:
curr += x
return result
# Time: O(n)
# Space: O(n)
# prefix sum, CodeChef Starters 146 - Bouncing Ball (https://www.codechef.com/problems/BOUNCE_BALL)
class Solution2(object):
def countValidSelections(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
prefix[i+1] = prefix[i]+nums[i]
suffix = [0]*(len(nums)+1)
for i in reversed(xrange(len(nums))):
suffix[i] = suffix[i+1]+nums[i]
return sum(max(2-abs(prefix[i]-suffix[i+1]), 0) for i in xrange(len(nums)) if nums[i] == 0)