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 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;
    }

你可能感兴趣的:(单调队列,leetcode,java)