【每日一题Day80】LC1658将 x 减到 0 的最小操作数 | 滑动窗口

给定一个整数数组nums和一个整数x,每次操作可以从数组的两端移除一个元素并将其值从x中减去。问题求解的是使x减为0所需的最小操作数。通过计算数组的前缀和与后缀和,可以找到满足条件的子数组,动态调整左右边界以找到最小长度。若无法达到目标和,则返回-1。

将 x 减到 0 的最小操作数【LC1658】

You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.

Return the minimum number of operations to reduce x to exactly 0 if it is possible*, otherwise, return* -1.

跟周赛3252516. 每种字符至少取 K 个很像,所以很快就过啦 nice (在家过着每天是礼拜几都不知道的日子 还以为自己错过了周赛)

  • 思路:题意可以转化为数组前缀和+后缀和sum x x x的最小长度

    • 假设左侧取到 n u m s [ i ] nums[i] nums[i],右侧取到 n u m s [ j ] nums[j] nums[j],由于和一定,因此随着 i i i的增大, j j j也会增大,因此可以先记录符合条件的 i i i的最小位置,然后从大到小枚举 j j j,并使 i i i尽可能左移,当sum==x时,更新最小长度。
  • 实现

    class Solution {
        public int minOperations(int[] nums, int x) {
            int n = nums.length, res = Integer.MAX_VALUE;
            int sum = 0, l = -1;
            // 记录前缀和大于等于sum的最小左边界
            while (l + 1 < n && sum < x){
                sum += nums[++l];
            }
            // 如果最大前缀和小于x,那么不可能将x减小至0,返回-1
            if (sum < x){
                return -1;
            }else if (sum == x){
                res = l + 1;
            }
            for (int r = n - 1; r > l; r--){
                sum += nums[r];
                // 收缩左边界
                while (sum > x && l >= 0){
                    sum -= nums[l--];
                }
                if (sum == x) res = Math.min(res, l + 1 + n - r);
            }
            return res == Integer.MAX_VALUE ? - 1: res;
    
        }
    }
    
    • 复杂度
      • 时间复杂度: O ( n ) O(n) O(n)
      • 空间复杂度: O ( 1 ) O(1) O(1)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值