【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

思路:输出长度最小的和至少为K的子数组长度,K是正数,数组可负可正,首先用前缀和可以用deque为维护单调增队列遇到小的更新队列,遇到满足的则弹出队头,对第i个sum,更新队列直到队列都小于sum,然后更新队头直到队头相差小于k,每次都push i用下标来比较,实际上代码整体上跟所有的单调队列一样只不过需要用前缀和来过度

代码:

class Solution {
public:
    int shortestSubarray(vector& A, int K) {
        int n=A.size();
        int len=n+1;
        deque q;
        vector s(n+1);
        for(int i=0;i=s[q.front()]+K){
                len=min(len,i-q.front());
                q.pop_front();
            }
            q.push_back(i);
        }

        return len==n+1?-1:len;

    }
};

 

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