You are given an integer array
Return the minimum number of operations to reduce
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Output: -1
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 105 1 <= nums[i] <= 104 1 <= x <= 109
Contents
-
Solution 1 - Using sliding window technique, find the longest array whose target is 'sum of array - x'
As per the problem statement, we have to find minimum number of elements needed to reduce
So, in this approach, what we are going to do is, find a largest array whose sum is equal to
Implementation steps:
-
First, compute the sum of input array elements, call it
sum . -
Then, compute the
remainder =sum -x , and we are goind to find a subarray whose sum is equal toremainder , if there is any. -
Next, create two variables
left ,right that we will use to adjust the window,currentSum to store current window elements sum andlongest to keep track of longest subarray found so far when subarray sum is equal toremainder . -
Next, run a
while loop, whileright pointer is within the bounds array length, and do the following:-
Add current element to
currentSum . -
Immediately after adding current element to
currentSum , check it is greater than theremainder , if it is, then run anotherwhile loop and moveleft pointer and subtract left element value fromcurrentSum , as long asleft pointer did not go beyondright pointer (in case if input array has negative values). -
Next, check if
currentSum is equal toremainder , it it is, then take the current window sizeright - left +1 and compare it withlongest found so far, and updatelongest among these two. -
Next, increment
right pointer.
-
Add current element to
-
Finally, check if
longest is greater than 0, that means a subarray is found whose sum isremainder , then returnnums.length - longest , that gives minimum number of elements left whose value must be equal tox , and iflongest is not greater than 0, then return-1 .
Complexity Analysis:
Time complexity: Above code runs in O(n) time, where
Space complexity: O(1).
Above implementations source code can be found at