Loading...
You are given an array of positive integers nums and an integer target.
In one operation you may remove the leftmost or the rightmost element of nums and subtract its value from target. Each removal shrinks the array, so subsequent removals act on the elements that remain.
Return the minimum number of operations needed to make target exactly 0, or -1 if it cannot be done.
Input: nums = [1,1,4,2,3], target = 5
Output: 2
Explanation: Remove the two rightmost elements (3 then 2); their values sum to 5.
Input: nums = [5,6,7,8,9], target = 4
Output: -1
Explanation: No sequence of end removals sums to exactly 4.
Input: nums = [3,2,20,1,1,3], target = 10
Output: 5
Explanation: Remove the three rightmost elements (3, 1, 1) and the two leftmost (3, 2); the five removed values sum to 10.
nums.length ≤105nums[i] ≤104target ≤109Click "Run" to test with sample cases or "Submit" to run all tests.