1658. Minimum Operations to Reduce X to Zero - Medium
前往題目
想法
Sliding window
思路
這題要反著想,不要湊x
,要湊sum(nums) - x
-> target
- 雙指針從左邊開始
- 每個循環更新當前總和
- 如果比
target
大,移動左指針 - 如果找到和
target
相等的和,紀錄window
大小,找最大的window
- 最後回傳陣列大小減去最大
window
就是最少操作數
Code
class Solution {
public int minOperations(int[] nums, int x) {
int target = 0;
// Calculate the target number
for (int num : nums) {
target += num;
}
target -= x;
int curSum = 0; // Current sum
int maxWin = -1; // Max window
int l = 0;
for (int r = 0; r < nums.length; ++r) {
// Update current sum
curSum += nums[r];
// Larger than the target
while (l <= r && curSum > target) {
curSum -= nums[l];
++l;
}
// Equals to the target
if (curSum == target) {
maxWin = Math.max(maxWin, r - l + 1);
}
}
if (maxWin == -1) return -1;
return nums.length - maxWin;
}
}
1658. Minimum Operations to Reduce X to Zero - Medium
https://f88083.github.io/2024/07/23/1658-Minimum-Operations-to-Reduce-X-to-Zero/