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.
Example 1
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: total=11, target=11-5=6. Longest middle block summing to 6 is [1,1,4] (length 3), so answer = 5 - 3 = 2 (remove the last two elements 2 and 3).
Example 2
Input: nums = [5,6,7,8,9], x = 4
Output: -1
Explanation: No prefix+suffix sums to exactly 4, so it is impossible.
Example 3
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: target=30-10=20; the longest block summing to 20 is just [20] (length 1), so answer = 6 - 1 = 5.
Removing a prefix and a suffix that together sum to x is the same as keeping a contiguous middle block that sums to total - x. So instead of minimizing the elements removed, maximize the length of a middle subarray whose sum equals total - x; the answer is n minus that length. Because every value is positive, a sliding window finds the longest such subarray in one pass.
Run checks all cases above. Submit evaluates all test cases.