20922 - 겹치는 건 싫어

2025. 2. 17. 11:12PS/백준

문제

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

느낀점

기본적인 투 포인터 문제, while문으로도 접근할 수 있고 그냥 for 문으로도 접근할 수 있다. 풀이 후 엣지 케이스를 검토하여 풀이를 보완하는 작업을 먼저 갖자.

풀이

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int N, K;
    cin >> N >> K;
    vector<int> numList(N);
    vector<int> numCount(100001, 0);
    for (int i = 0; i < N; i++)
    {
        cin >> numList[i];
    }
    int cnt = 0;
    int maxLength = 0;
    int left = 0;
    for (int right = 0; right < N; right++)
    {
        numCount[numList[right]]++;
        cnt++;
        if (numCount[numList[right]] > K)
        {
            maxLength = max(maxLength, cnt - 1);
            while (true)
            {
                numCount[numList[left++]]--;
                cnt--;
                if (numCount[numList[right]] <= K)
                {
                    break;
                }
            }
        }
    }
    cout << max(maxLength, cnt);

    return 0;
}

'PS > 백준' 카테고리의 다른 글

1484 - 다이어트  (0) 2025.02.17
25916 - 싫은데요  (0) 2025.02.17
15565 - 귀여운 라이언  (0) 2025.02.17
2531 - 회전 초밥  (0) 2025.02.15
22857 - 가장 긴 짝수 연속한 부분 수열 (small)  (0) 2025.02.14