https://www.acmicpc.net/problem/30804
풀이
투 포인터 알고리즘을 활용하여, 시작점을 고정시켜놓고 끝점을 늘려나다가, 과일의 개수가 2개를 초과하면 시작점을 하나씩 앞으로 당겨오는 방식을 반복
과일의 개수가 2개를 초과하거나 주어진 배열 밖으로 벗어날 경우 구간의 길이를 구하여 max값을 업데이트해 준다
제출 코드
#include <iostream>
using namespace std;
int fruit[200001];
int fCount[10];
bool check()
{
int cnt = 0;
for (auto& f : fCount)
if (f > 0) cnt++;
return cnt <= 2;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, start = 0, end = 0, maxCount = 0;
cin >> n;
for (int i = 0; i < n; i++) // 입력받기
cin >> fruit[i];
while(start < n)
{
while(end < n)
{
fCount[fruit[end]]++;
if (!check()) break;
end++;
}
maxCount = max(maxCount, end - start);
end++;
fCount[fruit[start]]--;
start++;
}
cout << maxCount;
}
'Programing > 백준, 프로그래머스(C++)' 카테고리의 다른 글
[C++][백준 1697] 숨바꼭질(BFS) (0) | 2025.06.23 |
---|---|
[C++][백준 1389] 케빈 베이컨의 6단계 법칙(BFS, 플로이드 워셜) (0) | 2025.06.23 |
[C++][백준 17626] Four Squares (0) | 2025.06.19 |
[C++][백준 9095] 1, 2, 3 더하기 (DP) (0) | 2025.02.13 |
[C++][백준 2579] 계단 오르기 (DP) (0) | 2025.02.13 |