Minimum Operations to Reduce X to Zero

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`. Return the minimum number of operations to reduce `x` to exactly `0` if it is possible, otherwise return `-1`.

30:00

Minimum Operations to Reduce X to Zero
medium
Free written solution
Topics
Companies

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. Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise return -1.

Example 1:
Input: {"nums":[1,1,4,2,3],"x":5}
Output: 2
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1041 \leq \text{nums}[i] \leq 10^4

  • 1≤x≤1091 \leq x \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,1,4,2,3],"x":5}

Removing from both ends leaves a middle block. The removed parts must add to x = 5, so the kept block must add to 11 - 5 = 6. Find the LONGEST block with that sum.

the array as a ribbon of length 11

keep exactly 6

block sum must match the green bracket; whatever is outside it is what x removes

1

0

1

1

4

2

2

3

3

4

block sum / need

0 / 6

longest keep

-

operations

-

Variables
VariableValue
total11
x5
target6
DepthFunction Call
Stack empty
0/11