백준 2003번: 수들의 합 2

danbibibi·2022년 1월 4일
0

문제

문제 바로가기> 백준 2003번: 수들의 합 2

풀이

두 포인터를 사용하여 O(n) 시간 안에 문제를 해결할 수 있다.

#include <iostream>
using namespace std;

int main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    int n, m; cin>>n>>m;
    int arr[10001]={};
    for(int i=0; i<n; i++) cin>>arr[i];
    
    int low=0, high=0, sum=0, ans=0;
    while(1){
        if(m<=sum) sum-=arr[low++];
        else if(high==n) break;
        else sum+=arr[high++];
        if(sum==m) ans++;
    }
    cout<<ans;
}
profile
블로그 이전) https://danbibibi.tistory.com

0개의 댓글