백준2003: 수들의 합 2
문제
https://www.acmicpc.net/problem/2003
문제 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//수열의 size
int N = sc.nextInt();
//수열의 합(합이 M일때 check)
int M = sc.nextInt();
int[] seq = new int[N];
//수열 입력
for (int i = 0; i < N; i++) {
seq[i] = sc.nextInt();
}
int result = twoPointers(seq,M);
System.out.println(result);;
}
public static int twoPointers(int[] seq, int M) {
int p1 = 0;
int p2 = 0;
int sum = 0;
int cnt = 0;
while (true) {
if (sum > M) {
sum -= seq[p1++];
} else if (p2 == seq.length) {
break;
} else {
sum += seq[p2++];
}
if (sum == M) {
cnt += 1;
}
}
return cnt;
}
}
댓글남기기