LeetCode 862. Shortest Subarray with Sum at Least K(单调队列)

Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.

If there is no non-empty subarray with sum at least K, return -1.

Example 1:
Input: A = [1], K = 1
Output: 1
Example 2:
Input: A = [1,2], K = 4
Output: -1
Example 3:
Input: A = [2,-1,2], K = 3
Output: 3

Note:

1 <= A.length <= 50000
-10 ^ 5 <= A[i] <= 10 ^ 5
1 <= K <= 10 ^ 9

单调队列,左边满足条件时缩小window,右边加入新元素前删除不可能成为答案的元素。
 public int shortestSubarray(int[] a, int k) {
        int min = a.length + 1;
        int[] sum = new int[a.length+1];
        for (int i = 1; i <= a.length; i++) sum[i] = sum[i-1] + a[i-1];
        Deque<Integer> q = new ArrayDeque<>();
        q.addLast(0);
        for (int i = 1; i < sum.length; i++) {
            if (i < a.length && a[i] >= k) return 1;
            while (!q.isEmpty() && sum[i] - sum[q.peekFirst()] >= k) {
                int index = q.pollFirst();
                min = Math.min(min, i - index);
            }
            while (!q.isEmpty() && sum[i] <= sum[q.peekLast()]) {
                q.pollLast();
            }
            q.addLast(i);
        }
        return min == sum.length ? -1 : min;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值