1658. Minimum Operations to Reduce X to Zero

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
class Solution {
public int minOperations(int[] nums, int x) {
int n = nums.length;

int[] doubleNums = new int[n + n];
for (int i = 0; i < n; i++) {
doubleNums[i] = doubleNums[i + n] = nums[i];
}

int minOperations = Integer.MAX_VALUE / 2;

int windowSum = 0;
int i = 0;
for (int j = 0; j < doubleNums.length; j++) {
windowSum += doubleNums[j];

while (windowSum > x) {
windowSum -= doubleNums[i++];
}

// 注意需要排除掉非边界区间的元素和
if (windowSum == x && !(i >= 1 && j <= n - 2) && !(i >= n + 1 && j <= 2 * n - 2)) {
minOperations = Math.min(minOperations, j - i + 1);
}
}

return minOperations == Integer.MAX_VALUE / 2 || minOperations > nums.length ? -1 : minOperations;
}
}

References

1658. Minimum Operations to Reduce X to Zero