[백준/C++] 1806번: 부분합

-inn·2022년 1월 4일
0

백준

목록 보기
1/28

코드

#include<bits/stdc++.h>
using namespace std;

int n, s, num;
long long dp[100001];

int main() {
	cin >> n >> s;
	for (int i = 0; i < n; i++) {
		cin >> dp[i];
	}
	int ans = n + 1, st = 0, end = 0, sum = 0;	// 시작점, 끝점 포인터
	// for문 2개로 체크했더니 시간초과 -> 투포인터 
	while (st <= end) {
		if (sum >= s) {	// 현재 포인터의 합이 s보다 클 경우
			ans = min(ans, end - st);	// 최솟값 저장
			sum -= dp[st++];
		}
		else if (end == n)	// 끝까지 도달할 경우 종료
			break;
		else {  // 포인터의 합이 s보다 작을 경우
			sum += dp[end++];
		}
	}

	ans = (ans == n + 1 ? 0 : ans);
	cout << ans;

	return 0;
}
profile
☁️

0개의 댓글