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.
Examples
Example 1
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.
Example 2
Input: nums = [5,6,7,8,9], target = 4
Output: -1
Explanation: No sequence of end removals sums to exactly 4.
Example 3
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.
Constraints
1≤nums.length≤105
1≤nums[i]≤104
1≤target≤109
Loading editor...
Log in to run your code. Your draft is saved in this browser.Log inSign up