Suppose we have an array called nums and another value x. In one operation, we can either delete the leftmost or the rightmost element from the array and subtract the value from x. We have to find the minimum number of operations required to reduce x to exactly 0. If it is not possible then return -1.
So, if the input is like nums = [4,2,9,1,4,2,3] x = 9, then the output will be 3 because at first we have to delete left most element 4, so array will be [2,9,1,4,2,3] and x will be 5, then remove right most element 3, so array will be [2,9,1,4,2], and x = 2, then again either left from left or from right to make x = 0, and array will be either [2,9,1,4] or [9,1,4,2].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(nums, x): n = len(nums) leftMap = dict() leftMap = -1 left = 0 for i in range(n): left += nums[i] if left not in leftMap: leftMap[left] = i right = 0 ans = n + 1 for i in range(n, -1, -1): if i < n: right += nums[i] left = x - right if left in leftMap: ans = min(ans, leftMap[left] + 1 + n - i) if ans == n + 1: return -1 return ans nums = [4,2,9,1,4,2,3] x = 9 print(solve(nums, x))