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 ^ 51 <= K <= 10 ^ 9
Companies:
Facebook, Goldman Sachs
Related Topics:
Binary Search, Queue
Let P[i] = A[0] + ... A[i - 1] where i ∈ [1, N]. Our goal is to find the smallest y - x such that P[y] - P[x] >= K.
Let opt(y) be the largest x such that P[y] - P[x] >= K. Two key observations:
- If
x1 < x2andP[x1] >= P[x2], then we don't need to considerx1because ifP[y] - P[x1] >= KthenP[y] - P[x2]must>= Kas well, andy - x2 < y - x1. - If
opt(y1) = x, then we do not need to consider thisxagain. If we find somey2 > y1withopt(y2) = x, then it represents an answery2 - xwhich is worse (larger) thany1 - x.
Rule 1 tells us that we just need to keep a strictly increasing sequence P[a] < P[b] < P[c]....
Rule 2 tells us that we can further shrink the sequence from the front whenever the front element P[x] has been used as opt(y).
Algorithm
Maintain a "monoqueue" of indices of P: a deque of indices x_0, x_1, ... such that P[x_0], P[x_1], ... is increasing.
When adding a new index y, we'll pop x_i from the end of the deque so that P[x_0], P[x_1], ..., P[y] will be increasing.
If P[y] >= P[x_0] + K, then (as previously described) we don't need to consider this x_0 again, and we can pop it from the front of the deque.
// OJ: https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
// Ref: https://leetcode.com/articles/shortest-subarray-with-sum-atleast-k/
class Solution {
public:
int shortestSubarray(vector<int>& A, int K) {
int N = A.size(), ans = INT_MAX;
vector<long> P(N + 1);
for (int i = 0; i < N; ++i) P[i + 1] = P[i] + A[i];
deque<int> q;
for (int y = 0; y < P.size(); ++y) {
while (q.size() && P[y] <= P[q.back()]) q.pop_back();
while (q.size() && P[y] >= P[q.front()] + K) {
ans = min(ans, y - q.front());
q.pop_front();
}
q.push_back(y);
}
return ans == INT_MAX ? -1 : ans;
}
};