2024/10/26 灵茶题单 不定长滑动窗口
This commit is contained in:
parent
ec621a7da2
commit
89f34adbdc
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue