Skip to content

Commit f78f17a

Browse files
authored
Create 1658. Minimum Operations to Reduce X to Zero (Chayandas07#293)
2 parents a9e508d + 046de3a commit f78f17a

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
int minOperations(vector<int>& nums, int x) {
4+
int totalSum = 0;
5+
for (int num : nums)
6+
totalSum += num;
7+
int maxLength = -1, currSum = 0;
8+
for (int l = 0, r = 0; r < nums.size(); r++) {
9+
currSum += nums[r];
10+
while (l <= r && currSum > totalSum - x)
11+
currSum -= nums[l++];
12+
if (currSum == totalSum - x)
13+
maxLength = max(maxLength, r - l + 1);
14+
}
15+
return maxLength == -1 ? -1 : nums.size() - maxLength;
16+
}
17+
};

0 commit comments

Comments
 (0)