// 滑動視窗法 / Sliding-window approach:
// right 擴張視窗並累加 sum；當 sum >= target 時收縮 left 取最短長度。
// 因為元素皆為正數，sum 隨視窗大小單調變化，每個元素至多進出視窗一次，故為 O(n)。
// right grows the window; left shrinks it when sum >= target. All-positive values
// make sum monotonic, so each element enters/leaves once → O(n).
#include <vector>
#include <climits>     // 提供 INT_MAX / provides INT_MAX
using namespace std;

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        long sum = 0;                 // 當前視窗總和，用 long 防溢位 / running window sum, long to avoid overflow
        int left = 0;                 // 視窗左端索引 / left edge of the window
        int ans = INT_MAX;            // 最短長度，初始為「無限大」/ best length, initialized to "infinity"
        int n = nums.size();          // size() 回傳容器元素個數 / size() returns the element count

        // 範圍以外用傳統索引迴圈，方便同時用 left/right 計算長度 / index loop so we can compute length from left/right
        for (int right = 0; right < n; ++right) {
            sum += nums[right];       // 將右端新元素併入總和 / add the element at right into the sum

            // 視窗合格時不斷收縮左端 / shrink the left edge while the window still qualifies
            while (sum >= target) {
                ans = min(ans, right - left + 1);  // min 取較小者，更新最短長度 / min keeps the smaller length
                sum -= nums[left];                 // 移除最左元素 / remove the leftmost element
                ++left;                            // 左端右移 / move the left edge rightward
            }
        }

        // 三元運算子：沒找到就回傳 0 / ternary: return 0 when no window was ever valid
        return ans == INT_MAX ? 0 : ans;
    }
};
