ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • section3.3
    알고리즘 2025. 8. 13. 20:10
    N개의 수로 이루어진 수열이 주어집니다.
    이 수열에서 연속부분수열의 합이 특정숫자 M이 되는 경우가 몇 번 있는지 구하는 프로그램을 작성하세요.
    만약 N=8, M=6이고 수열이 다음과 같다면
    1 2 1 3 1 1 1 2
    합이 6이 되는 연속부분수열은 {2, 1, 3}, {1, 3, 1, 1}, {3, 1, 1, 1}로 총 3가지입니다.
    
    입력
    첫째 줄에 N(1≤N≤100,000), M(1≤M≤100,000,000)이 주어진다.
    수열의 원소값은 1,000을 넘지 않는 자연수이다.
    
    출력
    첫째 줄에 경우의 수를 출력한다.
    
    예시 입력 1
    8 6
    1 2 1 3 1 1 1 2
    예시 출력 1
    3

     

     

     

    SOLUTION

    public class Question4V2 {
        public static void main(String[] args) {
            Question4V2 T = new Question4V2();
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int m = sc.nextInt();
            int[] arr = new int[n];
    
            for (int i=0; i<n; i++) {
                arr[i] = sc.nextInt();
            }
    
            System.out.println(T.Solution(n, m, arr));
    
        }
    
        public int Solution(int n, int m, int[] arr) {
            int answer = 0;
            int sum = 0;
            int lt = 0;
            for (int rt = 0; rt < n; rt++) {
                sum += arr[rt];
                if (sum == m) {
                    answer ++;
                }
    
                while (sum >= m) {
                    sum -= arr[lt++];
                    if (sum == m) {
                        answer++;
                    }
                }
            }
            return answer;
        }
    
    }

    대충 어떻게 푸는지는 아는데 막상 해보려고 하니까 어렵다...

    자주 복습해서 눈에 익히기 

    728x90

    '알고리즘' 카테고리의 다른 글

    section3.5  (1) 2025.08.13
    section3.4  (1) 2025.08.13
    section3.2  (0) 2025.08.09
    section3.1  (2) 2025.08.09
    section4.3  (3) 2025.08.07
Designed by Tistory.