[알고리즘]/알고리즘
[알고리즘] 백준 2003번 : 수들의 합2 (실버3)
쿠릉쿠릉 쾅쾅
2022. 4. 14. 15:30
728x90
문제
https://www.acmicpc.net/problem/2003
📌 문제풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String firtLine = br.readLine();
StringTokenizer st = new StringTokenizer(firtLine, " ");
// 수열 개수
int N = Integer.parseInt(st.nextToken());
int[] arr = new int[N];
// 합
int M = Integer.parseInt(st.nextToken());
String secondLine = br.readLine();
st = new StringTokenizer(secondLine, " ");
for(int i=0; i<N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int start = 0;
int end = 0;
int sum = 0;
int count = 0;
// 투 포인터 알고리즘
while(true) {
if(M==sum) {
count++;
}
if(M<=sum) {
sum-=arr[start++];
continue;
}
if(end==N) {
break;
}
if(sum<M) {
sum+= arr[end++];
}
}
System.out.println(count);
}
}
728x90