---
# System prepended metadata

title: 209. Minimum Size Subarray Sum
tags: [Leetcode]

---


# 209. Minimum Size Subarray Sum
[209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) (<font color="#FFB800"> Medium</font> 通過率: 48.3%)



## 限制條件
<ul>
<li>1 <= target <= 10^9</li>
<li>1 <= nums.length <= 10^5</li>
<li>1 <= nums[i] <= 10^4</li>
</ul>




### 解法 1
利用兩個變數來框出子序列，在計算當中的總和找到最小長度的作為總和

- 時間複雜度: O(n)
- 空間複雜度: O(1)

```cpp!=
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int min_length = INT_MAX;
        int left = 0, sum = 0;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];
            while (sum >= target) {
                min_length = min(min_length, i - left + 1);
                if (min_length == 1) return 1; 
                sum -= nums[left++];
            }
        }


        return min_length == INT_MAX ? 0 : min_length;
    }
};

```
</int>