# LeetCode Minimum Size Subarray Sum

LeetCode Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous 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.

More practice:If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

```class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int n = nums.size(), left = 0, right = 0, sum = 0, ans = INT_MAX;
while(right < n) {
while (right < n&&sum < s)sum += nums[right++];
while (left <= right&&sum >= s) {
ans = min(ans, right - left);
sum -= nums[left++];
}
}
return ans == INT_MAX ? 0 : ans;
}
};
```

```class Solution {
private:
int searchRight(vector<int>& accuSum, int l, int r, int target) {
while (l <= r) {
int m = l + (r - l) / 2;
if (accuSum[m] == target)return m;
else if (accuSum[m] > target)r = m - 1;
else l = m + 1;
}
return l;
}
public:
int minSubArrayLen(int s, vector<int>& nums) {
int n = nums.size(), ans = INT_MAX;
vector<int> accuSum(n + 1, 0);
for (int i = 1; i <= n; ++i)accuSum[i] = accuSum[i - 1] + nums[i - 1];
for (int left = 0; left < n; ++left) {
int right = searchRight(accuSum, left, accuSum.size() - 1, accuSum[left] + s);
if (right == n + 1)break;
ans = min(ans, right - left);
}
return ans == INT_MAX ? 0 : ans;
}
};
```