본문 바로가기

프로그래밍/백준

백준 1806 - 부분합 (파이썬)

난이도

골드 4

유형

두 포인터

해결

간단한 두 포인터 문제이다. s보다 구간 합이 작으면 r을 증가, 반대면 l을 증가시켜주면 된다.

코드

from sys import stdin
input=stdin.readline

n,s=map(int,input().split())
arr=[*map(int,input().split())]
l=0
r=0
total=0
ans=100001

while l<n:
    if total<s and r<n:
        total+=arr[r]
        r+=1
    elif total>=s or r==n:
        if total>=s:
            ans=min(ans,r-l)
        total-=arr[l]
        l+=1
    
    
print(ans if ans!=100001 else 0)

좋은 / 비슷한 문제