Skip to content

Commit 52c1547

Browse files
authored
Create 862. Shortest Subarray with Sum at Least K
1 parent 437577e commit 52c1547

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
int shortestSubarray(vector<int>& nums, int k) {
4+
int n=nums.size();
5+
6+
// find the prefix sum of the given array nums -:
7+
// Size is n+1 to handle subarrays starting from index 0
8+
vector<long long>prefixSum(n+1,0);
9+
10+
// Calculating prefix sums
11+
for(int i=1; i<=n; i++){
12+
prefixSum[i]=prefixSum[i-1]+nums[i-1];
13+
}
14+
15+
// Make a deque (doubly-ended queue -: which allows us to add/remove ele.s
16+
// from both front/end side.
17+
deque<int>candiIdx;
18+
19+
int len=INT_MAX;
20+
21+
for(int i=0; i<=n; i++){
22+
// Remove candidates from front of deque where subarray sum meets target sum
23+
while(!candiIdx.empty() && prefixSum[i]-prefixSum[candiIdx.front()]>=k){
24+
len=min(len,i-candiIdx.front());
25+
candiIdx.pop_front();
26+
}
27+
// Maintain monotonicity by removing indices with larger prefix sums
28+
while(!candiIdx.empty() && prefixSum[i]<=prefixSum[candiIdx.back()]) {
29+
candiIdx.pop_back();
30+
}
31+
// Add current index to candidates
32+
candiIdx.push_back(i);
33+
}
34+
// Return -1 if no valid subarray found
35+
return len == INT_MAX ? -1 : len;
36+
}
37+
};

0 commit comments

Comments
 (0)