수들의 합 2 2003

LJM·2023년 2월 23일
0

백준풀기

목록 보기
113/259

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

i부터 j 까지의 합이 m이되는 경우를 찾는것이다

주의할것
i부터 i 까지의 합이 m이되는 경우도 있다

생각보다 까다로운 문제였다

다음 반례가 도움이 되었다

3 1
1 2 1
ans:2

투포인터로 풀었다
시간복잡도는 2N ?

import java.io.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] input = br.readLine().split(" ");

        int N = Integer.parseInt(input[0]);
        int M = Integer.parseInt(input[1]);

        int[] arr = new int[N];
        input = br.readLine().split(" ");
        for(int i = 0; i < N; ++i)
        {
            arr[i] = Integer.parseInt(input[i]);
        }

        int l = 0;
        int r = 0;
        int sum = arr[0];
        int ans = 0;
        while(true)
        {
            if(sum == M)
                ans++;

            if(l!=r && sum > M)//l 이 r을 넘지 못하게 막는다
            {
                sum -= arr[l];
                l++;
            }
            else//sum <= M
            {
                r++;
                if(r >= N)
                    break;
                sum += arr[r];
            }
        }

        System.out.println(ans);
    }
}
profile
게임개발자 백엔드개발자

0개의 댓글