638/670

638. Minimum Operations to Reduce X to Zero

Medium

You are given an array of positive integers nums and a positive integer x. One operation removes either the leftmost or the rightmost element that currently remains, and subtracts the removed value from x.

Return the fewest operations needed to bring x exactly to 0, or -1 if no sequence of end-removals can do it.

The array shrinks as you go — every operation always takes from whatever the current two ends are, so in total you end up chopping some prefix and some suffix of the original array.

Example 1:

Input: nums = [1, 1, 4, 2, 3], x = 5

Output: 2

Explanation: Take 3 from the right (x becomes 2), then take 2 from the right (x becomes 0). Two operations is the best possible.

Example 2:

Input: nums = [5, 6, 7, 8, 9], x = 4

Output: -1

Explanation: Every element is larger than 4, so the very first removal already overshoots zero.

Example 3:

Input: nums = [3, 2, 20, 1, 1, 3], x = 10

Output: 5

Explanation: Take 3 and 2 from the left plus 3, 1, and 1 from the right: 3 + 2 + 3 + 1 + 1 = 10, using 5 operations and leaving only [20] behind.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁴
  • 1 ≤ x ≤ 10⁹

Hints:

Removals only ever come off the two ends, so whatever survives is one contiguous middle block. Reducing x to exactly 0 means the removed prefix plus the removed suffix sums to exactly x.

Flip the objective: minimizing removed elements is the same as maximizing the length of a kept middle subarray whose sum equals total(nums) − x.

Every value is positive, so a sliding window finds that longest subarray in one pass: extend the right edge, and shrink from the left while the window sum exceeds the target.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 1, 4, 2, 3], x = 5

Expected output: 2