From 209.Minimum Size Subarray Sum

Description

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray[numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Solution

209.长度最小的子数组

Credit to Programmercarl

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        # define a super large number
        res = float("inf")
        Sum = 0
        index = 0
        for i in range(len(nums)):
            Sum += nums[i]
            while Sum >= target:
                res = min(res, i-index+1)
                Sum -= nums[index]
                index += 1
        return 0 if res==float("inf") else res