본문 바로가기

코딩테스트/백준

[백준-자바] 2003번 수들의 합 2 / 2022.06.04

 

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

 

2003번: 수들의 합 2

첫째 줄에 N(1 ≤ N ≤ 10,000), M(1 ≤ M ≤ 300,000,000)이 주어진다. 다음 줄에는 A[1], A[2], …, A[N]이 공백으로 분리되어 주어진다. 각각의 A[x]는 30,000을 넘지 않는 자연수이다.

www.acmicpc.net

 

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

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 M = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(br.readLine());
        int [] number = new int [N];
        int count = 0;
        for(int i=0; i<N; i++){
            number[i] = Integer.parseInt(st.nextToken());
        }
        int start = 0;
        int end = 0;
        int hap = 0;
        while(true){
            if(hap >= M){
                hap -= number[start++];
            } else if (end == N) break;
            else{
                hap += number[end++];
            }

            if(hap == M)
                count++;
        }
        System.out.println(count);
    }
}