이제 막 코테 공부해볼까 단계인 나한테 골드 문제를 어떤 할아버지가 시킴,,,
(무시하셈)
컴파일 에러는 BufferedReader 초기화할 때 InputStreamReader 빼먹고,,,
StringTokenizer 제대로 사용안해서 그런거임
런타임에러는 end_index가 배열 범위를 벗어나서
ArrayIndexOutOfBoundsException이 발생함
그래서 아래 코드 보면 else 구문에 아래와 같은 조건문을 추가함
if (end_index < n - 1)
배열의 끝에 도달하면 더 이상 end_index를 증가시키지 않고
break문으로 while 루프 종료핑
import java.io.*;
import java.util.*;
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 m = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int start_index = 0;
int end_index = 0;
int sum = arr[0];
int minLength = Integer.MAX_VALUE;
while (end_index < n) {
if (sum >= m) {
minLength = Math.min(minLength, end_index - start_index + 1);
sum -= arr[start_index];
start_index++;
} else {
if (end_index < n - 1) {
end_index++;
sum += arr[end_index];
} else {
break;
}
}
}
if (minLength == Integer.MAX_VALUE) {
System.out.println(0);
} else {
System.out.println(minLength);
}
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준 2750번, 1427번] 정렬(Java) (0) | 2024.10.24 |
---|---|
[백준 1874번, 2164번] 스택과 큐(Java) (0) | 2024.10.21 |
[백준 2018번, 1940번] 투 포인터(Java) (1) | 2024.10.19 |
[백준 11659번] 구간 합(Java) (2) | 2024.10.18 |
[백준 11720번, 1546번] 배열과 리스트(Java) (6) | 2024.10.17 |