알고리즘/백준

[백준 1806번] 부분합(Java)

이채림 2024. 10. 20. 23:51

이제 막 코테 공부해볼까 단계인 나한테 골드 문제를 어떤 할아버지가 시킴,,,

 

 

 

(무시하셈)

컴파일 에러는 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);
        }
    }
}