- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/minimum-size-subarray-sum/
- topics: Sliding Window
Given an array of positive integers nums
and a positive integer target
, return the minimal length of a subarray whose sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
window_sum = 0
ans = float('inf')
current_window_size = 0
for i in range(len(nums)):
window_sum += nums[i]
current_window_size += 1
while window_sum >= target:
current_window_size -= 1
ans = min(ans, current_window_size + 1)
window_sum -= nums[i - current_window_size]
return ans if ans < float('inf') else 0