Skip to content

Commit fc06269

Browse files
authored
Create minimum-operations-to-reduce-x-to-zero.py
1 parent 5044fe8 commit fc06269

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def minOperations(self, nums, x):
6+
"""
7+
:type nums: List[int]
8+
:type x: int
9+
:rtype: int
10+
"""
11+
target = sum(nums)-x
12+
result = -1
13+
curr = left = 0
14+
for right in xrange(len(nums)):
15+
curr += nums[right]
16+
while left < len(nums) and curr > target:
17+
curr -= nums[left]
18+
left += 1
19+
if curr == target:
20+
result = max(result, right-left+1)
21+
return len(nums)-result if result != -1 else -1

0 commit comments

Comments
 (0)