Problem solving

백준 2003번 수들의 합 2 (Python 3)

storkbear 2022. 9. 1. 15:19

Baekjoon online judge 2003번 파이썬

 

링크

https://www.acmicpc.net/problem/2003

 

2003번: 수들의 합 2

첫째 줄에 N(1 ≤ N ≤ 10,000), M(1 ≤ M ≤ 300,000,000)이 주어진다. 다음 줄에는 A[1], A[2], …, A[N]이 공백으로 분리되어 주어진다. 각각의 A[x]는 30,000을 넘지 않는 자연수이다.

www.acmicpc.net

두 포인터 문제

i==j 인 경우도 카운트 (a[left:right] slicing에서 right==left+1 이면 a[left] 가 된다.)

 

소스코드

import sys

input = sys.stdin.readline

n, m = map(int, input().split())
a = list(map(int, input().split()))

left = 0
right = 1

cnt = 0

while left <= right and right <= n:
    acc = sum(a[left:right])

    if acc == m:
        cnt += 1
        right += 1
    elif acc < m:
        right += 1
    else:
        left += 1

print(cnt)