[ BOJ / C++ ] 1806번 부분합

황승환·2021년 7월 22일
0

C++

목록 보기
22/65

이번 문제는 투 포인터 알고리즘으로 쉽게 풀 수 있는 문제였다. 이중 for문으로도 해결 가능하지만 시간 제한에 걸리게 된다.
투 포인터 알고리즘

  • start, end 두 포인터를 두고 while문을 실행시킨다.
  • 만약 sum이 s보다 크거나 같다면 출력값을 저장하는 cnt에 넣는다. 이때 기존의 cnt와 비교하여 더 작은 것을 넣는다. 그리고 start포인터를 증가시킨다.
  • end가 n과 같아지면 while문을 탈출한다.
  • 이외의 경우에는 end포인터를 증가시킨다.

Code

#include <iostream>
#include <algorithm>
#define MAX 100001
using namespace std;

int n, s;
int arr[MAX];
int cnt=MAX;
int sum=0;

int Min(int a, int b){
    if(a>b)
        return b;
    else
        return a;
}

void Input(){
    cin>>n>>s;
    for(int i=0; i<n; i++){
        cin>>arr[i];
    }
}

void Solution(){
    int start=0;
    int end=0;
    while(start<=end){
        if(sum>=s){
            cnt=Min(cnt, end-start);
            sum-=arr[start++];
        }
        else if(end==n)
            break;
        else
            sum+=arr[end++];
    }
    if(cnt==MAX)
        cout<<0<<endl;
    else{
        cout<<cnt<<endl;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    Input();
    Solution();
    return 0;
}

profile
꾸준함을 꿈꾸는 SW 전공 학부생의 개발 일기

0개의 댓글