- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1658.java
29 lines (28 loc) · 1.03 KB
/
_1658.java
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
packagecom.fishercoder.solutions.secondthousand;
publicclass_1658 {
publicstaticclassSolution1 {
/*
* credit: https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/936074/JavaPython-3-Sliding-window%3A-Longest-subarray-sum-to-the-target-sum(nums)-x.
*/
publicintminOperations(int[] nums, intx) {
intsum = 0;
for (intn : nums) {
sum += n;
}
inttarget = sum - x;
intlen = nums.length;
intsize = Integer.MIN_VALUE;
for (intleft = -1, right = 0, windowSum = 0; right < len; right++) {
windowSum += nums[right];
while (left + 1 < len && windowSum > target) {
left++;
windowSum -= nums[left];
}
if (windowSum == target) {
size = Math.max(size, right - left);
}
}
returnsize < 0 ? -1 : len - size;
}
}
}