diff --git a/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1658.java b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1658.java new file mode 100644 index 0000000..da09717 --- /dev/null +++ b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1658.java @@ -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; + } +}