contains category wise problems(data structures, competitive) of popular platforms.
View the Project on GitHub mayankdutta/category-wise-problems
1658. Minimum Operations to Reduce X to Zero
left
and right
which make sum = x
.sum = TOTAL_SUM - x
int minOperations(vector<int>& nums, int x) {
int ans = 0;
int l = 0;
int n = nums.size();
int sum = 0;
if (x == accumulate(nums.begin(), nums.end(), 0)) {
return nums.size();
}
int target = accumulate(nums.begin(), nums.end(), 0) - x;
for (int r = 0; r < n; r++) {
sum += nums[r];
while (l <= r && sum > target) {
sum -= nums[l++];
}
if (sum == target) {
ans = max(ans, r - l + 1);
}
}
if (ans == 0)
return -1;
return n - ans;
}