forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path209.cpp
More file actions
26 lines (22 loc) · 715 Bytes
/
209.cpp
File metadata and controls
26 lines (22 loc) · 715 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int n = nums.size();
int ans = INT_MAX;
int l = 0,r=0;
int sum = 0;
while (r<n){
sum+=nums[r];
while (sum>=s){
ans= min(ans,r-l+1);
sum-=nums[l++];
}
r++;
}
return (ans != INT_MAX) ? ans : 0;
}
};
//======================================================
//Time complexity of the above algorithm asymptotically: O(n), n is the size of the input array.
//The reason is because in the worse case, every element will be visited only twice.
//Space complexity: O(1), constant