본문 바로가기

알고리즘

[백준] BOJ1806 - 부분합 (JAVA)

https://www.acmicpc.net/problem/1806

 

1806번: 부분합

첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.

www.acmicpc.net

import java.util.*;
import java.io.*;

public class Main
{

    static int N,S;
    static int ans;

    static void start(int[] x){
        int start = 0;
        int end = 0;
        int sum = x[start];

        while(true){
            if(sum>=S){
                ans = Math.min(end-start+1,ans);
                sum -= x[start++];
            }
            else if(end==N-1) break;
            else sum += x[++end];
        }
    }

    public static void main(String args[]) throws Exception
    {
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       StringTokenizer st;

       int[] arr;
       ans = Integer.MAX_VALUE;

       st = new StringTokenizer(br.readLine());
       N = Integer.parseInt(st.nextToken());
       S = Integer.parseInt(st.nextToken());
       arr = new int[N];

       st = new StringTokenizer(br.readLine());
       for(int i=0;i<N;i++){
           arr[i] = Integer.parseInt(st.nextToken());
       }

       start(arr);
       if(ans==Integer.MAX_VALUE) ans = 0;

        System.out.println(ans);

    }
}

투포인터로 모든 경우를 탐색할 수 있다는 것을 이해하는데에 조금 오래 걸리긴 했지만, 이해를 완료하였다 !

공부를 할수록 이해하는 속도가 빨라지는 것이 뿌듯하고 재미있다.