 All Problems
Minimum Operations to Reduce X to Zero
medium
sliding window
prefix sum
arrays
amazon
google
facebook

You are given an integer array nums and an integer x. In one operation, you can remove either the leftmost or rightmost element from the array and subtract its value from x. Return the minimum number of operations to reduce x to exactly 0, or -1 if it's impossible.

Example 1:

Input: 1 1 4 2 3
x: 5
Output: 2
Explanation: Remove 1 from left and 3 from right.

Example 2:

Input: 5 6 7 8 9
x: 4
Output: -1

Constraints:

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

Input format: First line: space-separated array. Second line: x.

Output format: Minimum operations, or -1.

Run to check your code against the sample cases, or submit to run every case