LeetCode Solutions
862. Shortest Subarray with Sum at Least K
Time: $O(n)$ Space: $O(n)$
class Solution {
public:
int shortestSubarray(vector<int>& A, int K) {
const int n = A.size();
int ans = n + 1;
deque<int> q;
vector<long> prefix(n + 1);
for (int i = 0; i < n; ++i)
prefix[i + 1] = prefix[i] + A[i];
for (int i = 0; i < n + 1; ++i) {
while (!q.empty() && prefix[i] - prefix[q.front()] >= K)
ans = min(ans, i - q.front()), q.pop_front();
while (!q.empty() && prefix[i] <= prefix[q.back()])
q.pop_back();
q.push_back(i);
}
return ans <= n ? ans : -1;
}
};
class Solution {
public int shortestSubarray(int[] A, int K) {
final int n = A.length;
int ans = n + 1;
Deque<Integer> q = new ArrayDeque<>();
long[] prefix = new long[n + 1];
for (int i = 0; i < n; ++i)
prefix[i + 1] = (long) A[i] + prefix[i];
for (int i = 0; i < n + 1; ++i) {
while (!q.isEmpty() && prefix[i] - prefix[q.getFirst()] >= K)
ans = Math.min(ans, i - q.pollFirst());
while (!q.isEmpty() && prefix[i] <= prefix[q.getLast()])
q.pollLast();
q.addLast(i);
}
return ans <= n ? ans : -1;
}
}
class Solution:
def shortestSubarray(self, A: List[int], K: int) -> int:
n = len(A)
ans = n + 1
q = deque()
prefix = [0] + list(itertools.accumulate(A))
for i in range(n + 1):
while q and prefix[i] - prefix[q[0]] >= K:
ans = min(ans, i - q.popleft())
while q and prefix[i] <= prefix[q[-1]]:
q.pop()
q.append(i)
return ans if ans <= n else -1