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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int minLeft = 0;
int minRight = nums.size()-1;
int curRight = -1; //这个要注意
bool foundFlag = false;
int curSum = 0;
for (int i=0; i<nums.size(); i++) {
while (curRight != nums.size()) {
if (curSum >= s)
{
foundFlag = true;
if (curRight - i < minRight - minLeft) {
minLeft = i;
minRight = curRight;
}
break;
}
else
{
curRight++; //这里
curSum += nums[curRight];
}
}
curSum -= nums[i];
}
if (foundFlag)
return minRight-minLeft+1;
return 0;
}
};