-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1658.py
30 lines (26 loc) · 879 Bytes
/
1658.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
from typing import List
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
total = sum(nums)
if x == total:
return len(nums)
target = total - x
left, right = 0, 0
length = len(nums)
cur = 0
res = -1
while left < length and right < length:
if cur + nums[right] == target:
if right - left + 1 > res:
res = right - left + 1
cur -= nums[left]
left += 1
elif cur + nums[right] < target:
cur += nums[right]
right += 1
elif cur + nums[right] > target:
cur -= nums[left]
left += 1
return length - res if res != -1 else -1
if __name__ == '__main__':
print(Solution().minOperations([3,2,20,1,1,3], 10))