# Program to find minimum operations to reduce X to zero in Python

Suppose we have an array called nums and another value x. In one operation, we can either delete the leftmost or the rightmost element from the array and subtract the value from x. We have to find the minimum number of operations required to reduce x to exactly 0. If it is not possible then return -1.

So, if the input is like nums = [4,2,9,1,4,2,3] x = 9, then the output will be 3 because at first we have to delete left most element 4, so array will be [2,9,1,4,2,3] and x will be 5, then remove right most element 3, so array will be [2,9,1,4,2], and x = 2, then again either left from left or from right to make x = 0, and array will be either [2,9,1,4] or [9,1,4,2].

To solve this, we will follow these steps −

• n := size of nums
• leftMap := a new map
• leftMap := -1
• left := 0
• for i in range 0 to n - 1, do
• left := left + nums[i]
• if left is not in leftMap, then
• leftMap[left] := i
• right := 0
• ans := n + 1
• for i in range n to 0, decrease by 1, do
• if i < n, then
• right := right + nums[i]
• left := x - right
• if left is present in leftMap, then
• ans := minimum of ans and leftMap[left] + 1 + n-i
• if ans is same as n + 1, then
• return -1
• return ans

## Example

Let us see the following implementation to get better understanding −

def solve(nums, x):
n = len(nums)

leftMap = dict()
leftMap = -1
left = 0
for i in range(n):
left += nums[i]
if left not in leftMap:
leftMap[left] = i

right = 0
ans = n + 1
for i in range(n, -1, -1):
if i < n:
right += nums[i]
left = x - right
if left in leftMap:
ans = min(ans, leftMap[left] + 1 + n - i)
if ans == n + 1:
return -1
return ans

nums = [4,2,9,1,4,2,3]
x = 9
print(solve(nums, x))

## Input

[4,2,9,1,4,2,3], 9


## Output

3

Updated on: 05-Oct-2021

229 Views 