// 滑動視窗法 / Sliding-window approach:
// 右指針 right 擴張視窗並累加總和；一旦總和 >= target，
// 就盡量收縮左指針 left 以求最短視窗，邊收縮邊更新答案。
// right expands the window and grows the sum; once sum >= target,
// shrink left as far as possible to minimize length, updating the answer.
#include <limits.h>   // 提供 INT_MAX 常數 / provides the INT_MAX constant

int minSubArrayLen(int target, int* nums, int numsSize) {
    long sum = 0;        // 當前視窗總和；用 long 避免最壞情況累加溢位 / current window sum; long avoids overflow
    int left = 0;        // 視窗左端索引 / left edge index of the window
    int ans = INT_MAX;   // 目前找到的最短長度，INT_MAX 代表「還沒找到」/ best length so far; INT_MAX means "none yet"

    // right 從 0 掃到尾，逐一把元素納入視窗右端 / move right across the array, adding each element
    for (int right = 0; right < numsSize; right++) {
        sum += nums[right];   // 把新元素加入視窗總和 / include the new element in the window sum

        // 只要視窗合格，就持續從左邊收縮 / while the window qualifies, keep shrinking from the left
        while (sum >= target) {
            int len = right - left + 1;   // 當前視窗長度（含兩端，故 +1）/ current window length, inclusive so +1
            if (len < ans) ans = len;     // 更新最短長度 / record a shorter window if found
            sum -= nums[left];            // 移除最左元素，準備縮小視窗 / drop the leftmost element
            left++;                       // 左端右移一格 / advance the left edge
        }
    }

    // 若 ans 從未被更新，表示無合格子陣列，依題意回傳 0 / if never updated, no valid subarray exists → return 0
    return ans == INT_MAX ? 0 : ans;
}
