-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminimumSizeSubarraySum.cpp
More file actions
46 lines (36 loc) · 1.34 KB
/
Copy pathminimumSizeSubarraySum.cpp
File metadata and controls
46 lines (36 loc) · 1.34 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Source : https://leetcode.com/problems/minimum-size-subarray-sum/
// Author : weekend27
// Date : 2015-12-03
/**********************************************************************************
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
**********************************************************************************/
// How to do it:
// two pointers, sliding window
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int len = nums.size();
if (len == 0)
return 0;
int minLen = len + 1;
int start = 0, end = 0, sum = 0;
while(end < len){
while(sum < s && end < len){
sum += nums[end];
end++;
}
while(sum >= s && start < len){
minLen = min(minLen, end-start);
if (minLen == 1)
return minLen;
sum -= nums[start];
start++;
}
if (sum >= s)
minLen = min(minLen, end-start);
}
return minLen == (len + 1) ? 0 : minLen;
}
};