https://leetcode.cn/problems/minimum-size-subarray-sum/description/?envType=study-plan-v2&envId=top-interview-150

 

package leetcode150

import "testing"

func TestMinSubArrayLen(t *testing.T) {
    target := 15
    nums := []int{5, 1, 3, 5, 10, 7, 4, 9, 2, 8}
    res := minSubArrayLen(target, nums)
    println(res)
}

func minSubArrayLen(target int, nums []int) int {
    if len(nums) == 0 {
        return 0
    }
    i, j, total, ans := 0, 1, nums[0], 0
    for i < j {
        if total >= target {
            if ans == 0 || ans > j-i {
                ans = j - i
                if ans == 1 {
                    return ans
                }
            }
            total -= nums[i]
            i++
            continue
        } else if total < target && j == len(nums) {
            break
        }

        if j != len(nums) {
            total += nums[j]
            j++
        }
    }

    return ans
}