Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The question here asks to minimize the operations to reduce X to zero by taking elements from either side. Let us take total sum of the array be totalSum. If X is reduced from either side, means remaining array will have sum equal to totalSum-X. As operations has to be minimized, so this question is equivalent to finding maximum size subarray having sum as totalSum-X.
- */
- class Solution:
- def minOperations(self, nums: List[int], x: int) -> int:
- total=sum(nums)
- target=total-x
- cur=0
- l=0
- i=0
- ans=-math.inf
- for i in range(len(nums)):
- cur+=nums[i]
- while cur>target and l<=i:
- cur-=nums[l]
- l+=1
- if cur==target:
- ans=max(ans,i-l+1)
- if ans==-math.inf:
- return -1
- return len(nums)-ans;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement