> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/sliding-window/medium/1658.-minimum-operations-to-reduce-x-to-zero.md).

# 1658. Minimum Operations to Reduce X to Zero

## Problem Statement

<br>

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`.

&#x20;

**Example 1:**

<pre><code><strong>Input: nums = [1,1,4,2,3], x = 5
</strong><strong>Output: 2
</strong><strong>Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [5,6,7,8,9], x = 4
</strong><strong>Output: -1
</strong></code></pre>

**Example 3:**

<pre><code><strong>Input: nums = [3,2,20,1,1,3], x = 10
</strong><strong>Output: 5
</strong><strong>Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
</strong></code></pre>

&#x20;

**Constraints:**

* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
* `1 <= x <= 109`

## Intuition

```
Approach:

We want elements from end
If we take middle window target and subtract, that might give us answer

Eg ->  1 1 4 2 3  X=5
Take total(arrsum)-X = 6
Find 6 using Sliding Window

(1 1 4) 2 3
subtarct window size
```

### Links

<https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/description/?envType=daily-question&envId=2023-09-20>

### Video Links

<https://www.youtube.com/watch?v=xumn16n7njs&ab_channel=NeetCodeIO>

### Approach 1:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int n = nums.size();
        int sum = accumulate(nums.begin(), nums.end(), 0);
        int low=0, high=0, window_sum=0, ans = INT_MAX, target=sum-x;
        if(target < 0)
            return -1;

        while(high<n){
            window_sum += nums[high];
            while(window_sum > target)
                window_sum -= nums[low++];

            if(window_sum == target)
                ans = min(ans, n-(high-low+1));

            high++;
        }

        return ans == INT_MAX ? -1 : ans;
    }
};
```

{% endcode %}

### Approach 2:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

###
