ffinn92 / Keep-at-solve-it

꾸준히 알고리즘 풀기 위한 스터디 저장소입니다.
2 stars 3 forks source link

[220623][BC][인프런](3-4) 연속 부분수열 #79

Closed honeySleepr closed 2 years ago

honeySleepr commented 2 years ago

📌 문제

⭐️ 아이디어

🤔 고민한 내용

💪 새롭게 배운 내용

🆘 이해가 어려운 내용

❌ 해결하지 못한 이유

✅ 본인 풀이

image

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class P0304 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] split1 = br.readLine().split("\\s");
        String[] split2 = br.readLine().split("\\s");

        int n = Integer.parseInt(split1[0]);
        int targetValue = Integer.parseInt(split1[1]);
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(split2[i]);
        }
        int start = 0;
        int a = 0;
        int sum = 0;
        int count = 0;

        while (a < n) {
            while (sum < targetValue && a < n) {
                sum += arr[a];
                a++;
            }

            while (sum >= targetValue && start < n) {
                if (sum == targetValue) {
                    count++;
                }
                sum -= arr[start];
                start++;
            }
        }

        System.out.println(count);
    }
}
/*
8 3
1 2 1 3 1 1 1 2
* */

참고한 자료