BOJ 1806 부분합
BOJ 1806 부분합
https://www.acmicpc.net/problem/1806
문제
10,000 이하의 자연수로 이루어진 길이 N짜리 수열이 주어진다. 이 수열에서 연속된 수들의 부분합 중에 그 합이 S 이상이 되는 것 중, 가장 짧은 것의 길이를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.
출력
첫째 줄에 구하고자 하는 최소의 길이를 출력한다. 만일 그러한 합을 만드는 것이 불가능하다면 0을 출력하면 된다.
예제 입력 1
10 15 5 1 3 5 10 7 4 9 2 8
예제 출력 1
2
코드
간단한 투 포인터 문제였다.
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
43
44
45
46
47
48
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int S = Integer.parseInt(st.nextToken());
int[] sequence = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
sequence[i] = Integer.parseInt(st.nextToken());
}
int answer = Integer.MAX_VALUE;
int sum = 0;
int lIdx = 0;
int rIdx = 0;
while (rIdx < N) {
if(sum < S) {
sum += sequence[rIdx];
rIdx++;
} else {
answer = Integer.min(answer, rIdx - lIdx);
sum -= sequence[lIdx];
lIdx++;
}
}
// rIdx가 수열의 마지막일 때까지 확인 후, lIdx를 1씩 줄여가며 S 이상이 되는 부분합의 최소 길이를 검사
while (sum >= S) {
answer = Integer.min(answer, rIdx - lIdx);
sum -= sequence[lIdx];
lIdx++;
}
if(answer == Integer.MAX_VALUE) {
answer = 0;
}
System.out.println(answer);
}
}
This post is licensed under CC BY 4.0 by the author.