September 23Medium
Minimum operations to reduce x to zero
- Array
- Hash Table
- Binary Search
- Sliding Window
- Prefix Sum
Problem
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
Solution
class Solution:
def minOperations(self, nums: list[int], x: int) -> int:
# max subarray such that its sum = total - x
length = 0
start = 0
total = sum(nums)
if total < x:
return -1
if total == x:
return len(nums)
curr_total = 0
for end in range(len(nums)):
curr_total += nums[end]
while curr_total > (total - x):
curr_total -= nums[start]
start += 1
if curr_total == total - x:
length = max(length, end - start + 1)
return len(nums) - length if length else -1