132. 수들의 합 2

아현·2021년 7월 6일
0

Algorithm

목록 보기
133/400
post-custom-banner

백준



1. Python



n, m = map(int, input().split())
data = list(map(int, input().split()))

cnt = 0
s = 0
end = 0

for start in range(n) :
    while s < m and end < n :
        s += data[end]
        end += 1
    if s == m :
        cnt += 1
    s -= data[start]

print(cnt)




2. Java



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

public class Main {
    private static int N, M;
    private static int[] A;

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        A = new int[N];

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

        int answer = 0;
        // 완전탐색 비슷하게
        // 투포인터는??
        /*
        int s = 0, e = 0, sum = 0;
        while (s < N && e < N) {
            for ( ; e < N ; e++) {
                sum += A[e];
                if (sum == M) {
                    answer++;
                    e++;
                    break;
                }
                else if (sum > M) {
                    e++;
                    break;
                }
            }
            while (s < N && sum >= M) {
                sum -= A[s];
                s++;
                if (sum == M) {
                    answer++;
                }
            }
        }
        */
        int sum = 0;
        for (int s = 0, e = 0 ; e < N ; e++) {
            sum += A[e];
            while (sum > M) {
                sum -= A[s];
                s++;
            }
            if (sum == M) answer++;
        }
        System.out.println(answer);
    }
}



profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글