[LeetCode] Minimum Operations to Reduce X to Zero

1658. Minimum Operations to Reduce X to Zero

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int minOperations(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--];
} else if(left){
val -= nums[--left];
} else {
break;
}
}

return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/26/PS/LeetCode/minimum-operations-to-reduce-x-to-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.