Skip to content

Minimum Size Subarray Sum

LeetCode

01 · Question

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is at least target. If there is no such subarray, return 0.

02 · Solution

Reference solution

1def minSubArrayLen(target: int, nums: List[int]) -> int:
2 l = 0
3 cur = 0
4 res = float('inf')
5
6 for r in range(len(nums)):
7 cur += nums[r]
8 while cur >= target:
9 res = min(res, r - l + 1)
10 cur -= nums[l]
11 l += 1
12
13 return 0 if res == float('inf') else res