2024/10/26 灵茶题单 不定长滑动窗口

This commit is contained in:
Cool 2024-10-26 16:40:35 +08:00
parent ec621a7da2
commit 89f34adbdc
1 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,36 @@
package com.cool.ling_cha_mount.sliding_windows;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/10/26/16:40
* @Description: 1658. x 减到 0 的最小操作数
* @Score 1817
*/
public class Num1658 {
public int minOperations(int[] nums, int x) {
int sum = 0;
for (int num : nums) {
sum += num;
}
int target = sum - x;
if (target < 0) {
return -1;
}
int res = -1;
int left = 0;
sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
while (sum > target && left < nums.length) {
sum -= nums[left++];
}
if (sum == target) {
res = Math.max(res, i - left + 1);
}
}
return res < 0 ? -1 : nums.length - res;
}
}