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.
Function Signature
def min_operations(nums: list[int], x: int) -> int:
Rules
-
Each operation removes the current first or last element of
nums
. The remaining elements keep their order, so later operations see the new ends.
-
x
must reach exactly
0
. A removal that takes
x
below
0
cannot be undone.
-
Removing every element is allowed. If
sum(nums) == x
, the answer is
len(nums)
.
-
Return
-1
when no sequence of removals brings
x
to exactly
0
.
Constraints
-
1 <= len(nums) <= 10^5
-
1 <= nums[i] <= 10^4
-
1 <= x <= 10^9
Examples
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Removing the last two elements (3, then 2) subtracts exactly 5. Neither end element on its own equals 5, so one operation is not enough.
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Every element is larger than 4, so the first removal from either end already takes x below zero.
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Removing the 20 would push x below zero, so it has to stay. The other five elements sum to exactly 10: remove 3 and 2 from the left and 3, 1 and 1 from the right.