From 89f34adbdcf83833b27f67ffddd36d5dc95bc596 Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Sat, 26 Oct 2024 16:40:35 +0800 Subject: [PATCH] =?UTF-8?q?2024/10/26=20=E7=81=B5=E8=8C=B6=E9=A2=98?= =?UTF-8?q?=E5=8D=95=20=E4=B8=8D=E5=AE=9A=E9=95=BF=E6=BB=91=E5=8A=A8?= =?UTF-8?q?=E7=AA=97=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sliding_windows/Num1658.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/com/cool/ling_cha_mount/sliding_windows/Num1658.java 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; + } +}