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
슬라이딩 윈도우 형태로 문제를 풀었습니다
슬라이딩 윈도우의 크기를 왼쪽, 오른쪽을 조절하면서 연속된 합이 target값과 같은지 비교하면됩니다!
1. 슬라이딩 윈도우의 합이 target보다 크거나 같다면 왼쪽 요소를 빼주고, window_start 인덱스를 1증가시켜줍니다. (구간이 작아지는 효과)
2. 슬라이딩 윈도우의 합이 target보다 작다면 오른쪽 요소를 window_sum에 더해주고, window_end 인덱스를 1증가시켜줍니다. (구간이 길어지는 효과)
3. 슬라이딩 윈도우의 합이 target이면 ans를 1 증가시켜줍니다.
4. window_end 인덱스값이 리스트의 사이즈보다 작을때까지만 1~3 작업을 반복합니다.
Python Code
def solve(lis, target):
ans = 0
size = len(lis)
window_start, window_end = 0, 0
window_sum = 0
while True:
if window_sum >= target:
window_sum -= lis[window_start]
window_start += 1
else:
if window_end == size:
break
window_sum += lis[window_end]
window_end += 1
if window_sum == target:
ans += 1
return ans
if __name__ == "__main__":
N, M = map(int, input().split())
lis = list(map(int, input().split()))
print(solve(lis, M))
'Algorithm' 카테고리의 다른 글
[LeetCode] Python - 122. Best Time to Buy and Sell Stock II (0) | 2021.06.27 |
---|---|
[LeetCode] Python - 121. Best Time to Buy and Sell Stock (0) | 2021.06.27 |
[LeetCode] Python - 720. Longest Word in Dictionary (0) | 2021.06.25 |
[LeetCode] Python - 98. Validate Binary Search Tree (0) | 2021.06.18 |
[LeetCode] Java, Python - 94. Binary Tree Inorder Traversal (0) | 2021.06.18 |