209. Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
Solution: Two Pointers
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
min_len = float('inf')
sum = 0
slow = 0
fast = 0
while fast < len(nums):
sum += nums[fast]
fast += 1
while sum >= s:
min_len = min(min_len, fast - slow)
sum -= nums[slow]
slow += 1
return 0 if min_len == float('inf') else min_len