Minimum Operations to Reduce X to Zero

Medium Topics Company Tags

In one operation, remove either the first or the last remaining element of nums and subtract its value from x. Return the fewest operations needed to make x exactly zero. If no sequence of these removals works, return -1.

Example 1:

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

Output: 2

Explanation: Remove 2 from the left and 3 from the right. Their sum is 5, so two operations suffice. Neither endpoint alone equals 5.

Example 2:

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

Output: 2

Explanation: Remove both elements, whose sum is 2 + 3 = 5. This uses two operations and leaves an empty array.

Example 3:

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

Output: -1

Explanation: The initial endpoints are both 4. Removing either would overshoot x = 3, so no valid sequence exists.

Constraints:

  • 1 <= nums.length <= 100000
  • 1 <= nums[i] <= 10000
  • 1 <= x <= 1000000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.