https://www.acmicpc.net/problem/1806
1806번: 부분합
첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.
www.acmicpc.net
머리와 꼬리의 인덱스를 저장하고 그 사이에 있는 값들의 합을 구해야 합니다.
합이 S보다 크거나 같으면 꼬리를 한 칸 당겨오고, 작으면 머리를 앞으로 한 칸 뻗습니다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
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[] input = new int[N];
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < N; i++) {
input[i] = Integer.parseInt(st.nextToken());
} // end of input
int head = 0;
int tail = 0;
int sum = input[0];
int len = 123456;
while(len != 0) {
if(S <= sum) {
len = Math.min(len, head - tail);
sum -= input[tail++];
} else if(head + 1 < N) {
sum += input[++head];
} else break;
}
System.out.print(len == 123456 ? 0 : len + 1);
}
}
'OJ' 카테고리의 다른 글
[BOJ] 1306 달려라 홍준 (JAVA) (0) | 2022.12.29 |
---|---|
[BOJ] 13565 침투 (JAVA) (0) | 2022.12.28 |
[BOJ] 1726 로봇 (JAVA) (0) | 2022.12.26 |
[BOJ] 1240 노드사이의 거리 (JAVA) (0) | 2022.12.25 |
[BOJ] 16441 아기돼지와 늑대 (JAVA) (0) | 2022.12.23 |