File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
0892-shortest-subarray-with-sum-at-least-k Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments