알고리즘/수학문제

[백준] 2003번 수들의 합 2

VIPeveloper 2022. 5. 23. 13:40
728x90
반응형
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

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());
        int [] arr = new int[n];
        st = new StringTokenizer(br.readLine()," ");
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        solution(arr,m);
        System.out.println(cnt);
    }
    static int cnt;
    private static void solution(int[] arr,int m) {
        int s=0,e=0,sum=0;

        while (true){
            if(sum>=m){
                sum-= arr[s++];
            }else if(e == arr.length){
                break;
            }else {
                sum += arr[e++];
            }

            if(sum==m){
                cnt++;
            }
        }
    }
}
728x90
반응형