[백준] 부분합 (1806)

크타·2022년 11월 1일
0

백준

목록 보기
2/11


투 포인터의 대표적인 예제이다.
투 포인터 알고리즘은 리스트가 있을 때 start, end 2개의 포인터가 모두 0부터 시작한다. 조건에 해당하지 않으면 end + 1 해주고, 해당 되면 start + 1 하며 원하는 값을 구하는 알고리즘이다.
시간 복잡도는 O(N)

n, s = map(int, input().split())
nums = list(map(int, input().split()))
start, end = 0, 0
result = []
now = 0
while start < n and end <= n:
    if now < s:
        if end == n:
            break
        now += nums[end]
        end += 1
    if now >= s:
        result.append(end - start)
        now -= nums[start]
        start += 1

if result:
    print(min(result))
else:
    print(0)

0개의 댓글