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’s possible, otherwise, return -1.
classSolution { public: intminOperations(vector<int>& nums, int x){ int sz = nums.size(); int left = 0, right = sz - 1; int val = 0, res = INT_MAX; for(; left < sz && val + nums[left] <= x; left++) { val += nums[left]; } if(left == sz) return val == x ? left : -1; while(right != -1) { if(val == x) { res = min(res, left + sz - right - 1); } if(right && val + nums[right] <= x) { val += nums[right--]; } elseif(left){ val -= nums[--left]; } else { break; } }