Skip to content

Commit 9f154a1

Browse files
authored
Update Minimum Operations to Reduce X to Zero.java
1 parent b43550a commit 9f154a1

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed
Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
class Solution {
2-
public int minOperations(int[] nums, int x) {
3-
int totalSum = 0;
4-
for (int num : nums) {
5-
totalSum += num;
2+
public int minOperations(int[] nums, int x) {
3+
int sum = 0;
4+
for (int num : nums) {
5+
sum += num;
6+
}
7+
int max = -1;
8+
int left = 0;
9+
int curr = 0;
10+
int n = nums.length;
11+
for (int right = 0; right < n; right++) {
12+
curr += nums[right];
13+
while (curr > sum - x && left <= right) {
14+
curr -= nums[left++];
15+
}
16+
if (curr == sum - x) {
17+
max = Math.max(max, right - left + 1);
18+
}
19+
}
20+
return max != -1 ? n - max : -1;
621
}
7-
int max = -1;
8-
int left = 0;
9-
int current = 0;
10-
for (int right = 0; right < nums.length; right++) {
11-
current += nums[right];
12-
while (current > totalSum - x && left <= right) {
13-
current -= nums[left++];
14-
}
15-
if (current == totalSum - x) {
16-
max = Math.max(max, right - left + 1);
17-
}
18-
}
19-
return max != -1 ? nums.length - max : -1;
20-
}
2122
}

0 commit comments

Comments
 (0)