algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

minimum-size-subarray-sum-v2.py (973B)


      1 class Solution:
      2     def minSubArrayLen(self, target: int, nums: List[int]) -> int:
      3         
      4         left = 0
      5         right = 0
      6         current_sum = nums[0]
      7         shortest = 0
      8 
      9         def move_left():
     10             nonlocal current_sum, left
     11             current_sum -= nums[left]
     12             left += 1
     13         
     14         def move_right():
     15             nonlocal current_sum, right
     16             right += 1
     17             if right < len(nums):           
     18                 current_sum += nums[right]
     19 
     20         while right < len(nums):
     21             if current_sum >= target:
     22                 current_len = right - left + 1
     23                 if current_len < shortest or shortest == 0:
     24                     shortest = current_len
     25                     if left < right:
     26                         move_left()
     27                     else:
     28                         move_right()
     29                 else:
     30                     move_left()
     31             else:
     32                 move_right()
     33 
     34         return shortest