We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent bdb3617 commit d741ebeCopy full SHA for d741ebe
0892-shortest-subarray-with-sum-at-least-k/0892-shortest-subarray-with-sum-at-least-k.cpp
@@ -0,0 +1,27 @@
1
+class Solution {
2
+public:
3
+ int shortestSubarray(vector<int>& nums, int k) {
4
+ int n = nums.size();
5
+ deque<int> dq;
6
+ vector<long long> prefix(n + 1, 0);
7
+ for (int i = 0; i < n; i++) {
8
+ prefix[i + 1] = prefix[i] + nums[i];
9
+ }
10
+
11
+ int minLength = n + 1;
12
+ for (int i = 0; i <= n; i++) {
13
+ // Remove elements from deque if they satisfy the condition
14
+ while (!dq.empty() && prefix[i] - prefix[dq.front()] >= k) {
15
+ minLength = min(minLength, i - dq.front());
16
+ dq.pop_front();
17
18
+ // Remove elements from the back if the current prefix is smaller
19
+ while (!dq.empty() && prefix[i] <= prefix[dq.back()]) {
20
+ dq.pop_back();
21
22
+ dq.push_back(i);
23
24
+ return minLength == n + 1 ? -1 : minLength;
25
26
27
+};
0 commit comments