[백준 2003번] 수들의 합2

박형진·2023년 5월 21일
0

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


1. for start...

import sys

N, M = map(int, input().split())
lst = list(map(int, sys.stdin.readline().rstrip().split()))

ans = 0
SUM = 0
end = 0
for start in range(N):
	# end 를 가능한 만큼 이동
    while SUM < M and end < N:
        SUM += lst[end]
        end += 1
    if SUM == M:
        ans += 1
    SUM -= lst[start]
print(ans)

2. for end...

import sys

N, M = map(int, input().split())
lst = list(map(int, sys.stdin.readline().rstrip().split()))

ans = 0
SUM = 0
start = 0
for end in range(N):
    SUM += lst[end]

    if SUM < M:
        continue
    elif SUM == M:
        ans += 1
        SUM -= lst[start]
        start += 1
    elif SUM > M:
        while start < N and SUM > M:
            SUM -= lst[start]
            if SUM == M:
                ans += 1
            start += 1
print(ans)

# 1번 방식
for start in range(N) -> end 는 while문에서 처리
	...
    SUM -= lst[start]
# 2번 방식
for end in range(N) -> start 는 while문에서 처리
    SUM += lst[end]
    ...

"""
for 반복문의 변수로 사용되는 start 혹은 end은 += 1 연산으로만 이용되고
남은 start 혹은 end 를 while문을 통해 적절히 처리하는 것이 핵심이다.

(반복문이 진행됐다는 의미는 새로운 변수값을 활용해야 하는 상황이기 때문에 진행됐기 때문이다.)
"""

이 문제는 가능한 end를 증가시키고 for문을 통해 start를 한 칸씩 움직이는 방식이 훨씬 깔끔한 풀이가 나온다.

2번 방식은 억지로 힘든 방식으로 풀어보고 싶어서 풀어봤다.
중요한 점은 문제를 읽고 어느 방식이 더 효율적인지 생각해보는 것이다.

profile
안녕하세요!

0개의 댓글