Minimum Size Subarray Sum*
LeetCode 209
class Solution:
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
"""
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.
Kandane's Algorithm
i 與 j 在同一個位置 然後 j 一直往前找並且累加值直到 curSum "大於" 所求值
(不是大於等於喔 因為題目要求 sum ≥ s)
然後當前值減去 num[i] 然後 i 往前移
"""
i = j = curSum = 0
mini = math.inf
while j < len(nums):
if curSum + nums[j] < s:
curSum = curSum + nums[j]
j += 1
else:
mini = min(j-i+1, mini)
curSum = curSum - nums[i]
i += 1
return mini if mini != math.inf else 0
Last updated