LeetCode/Top Interview 150

209. Minimum Size Subarray Sum

hyunkookim 2024. 11. 29. 16:30

209. Minimum Size Subarray Sum

 

https://youtu.be/aYqYMIqZx5s?si=65RqKA5cewrGgD2Q

 

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        # 문제에서 'subarray'가 언급되면 슬라이딩 윈도우 문제일 가능성이 높음

        l, total = 0, 0  # l: 윈도우의 왼쪽 끝 인덱스, total: 현재 윈도우의 합
        res = float("inf")  # 결과 값을 저장할 변수. 최소 길이를 구하기 위해 초기값을 무한대로 설정

        # r은 윈도우의 오른쪽 끝 인덱스를 나타냄
        for r in range(len(nums)):
            total += nums[r]  # 현재 윈도우에 nums[r] 값을 추가하여 합을 업데이트

            # 윈도우 내 합이 target 이상이 될 때까지 반복
            while total >= target:
                # 현재 윈도우 길이(r - l + 1)를 기존 결과 값(res)와 비교하여 최소값을 저장
                res = min(r - l + 1, res)

                # 윈도우의 왼쪽 끝 값을 제외하여 윈도우 축소
                total -= nums[l]
                l += 1  # 윈도우의 왼쪽 끝을 오른쪽으로 이동

        # res 값이 갱신되지 않았다면 가능한 부분 배열이 없다는 뜻이므로 0을 반환
        return 0 if res == float("inf") else res

'LeetCode > Top Interview 150' 카테고리의 다른 글

30. Substring with Concatenation of All Words  (0) 2024.11.29
3. Longest Substring Without Repeating Characters  (0) 2024.11.29
15. 3Sum  (0) 2024.11.29
167. Two Sum II - Input Array Is Sorted  (0) 2024.11.29
125. Valid Palindrome  (0) 2024.11.28