겹치는 건 싫어 20922

LJM·2023년 3월 3일
0

백준풀기

목록 보기
123/259

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

K개 이하로 중복되는 정수들을 체크하는 부분이 어려웠다 K 초과할때 체크하는건 쉽지만
K보다 미만이 될때 체크하는건 어렵다고 생각했는데 그렇지 않다
K 초과 하는 정수가 하나라도 나오면 바로 l++하면서 K보다 초과한 녀석이 줄어들때만 체크하면 된다
K 초과 하는 정수가 2개 이상이라면 이 알고리즘으로 해결할 수 없다

예외처리 때문에 힘들었다;;

if(cntOverlap <= K)

이 조건문으로 해결할 수 있었다

import java.io.*;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] input = br.readLine().split(" ");

        int N = Integer.parseInt(input[0]);
        int K = Integer.parseInt(input[1]);

        input = br.readLine().split(" ");

        int[] arr = new int[N];
        for(int i = 0; i < N; ++i)
        {
            arr[i] = Integer.parseInt(input[i]);
        }

        int l = 0;
        int r = 0;
        int cntOverlap = 0;
        int[] ncnt = new int[200001];
        ncnt[arr[l]]++;

        int ans = 0;
        while(r+1 < N)
        {
            if(l < r && cntOverlap > K)
            {
                if(ncnt[arr[l]] > K)
                    cntOverlap--;

                ncnt[arr[l]]--;

                l++;
            }
            else//cntOverlap < K
            {
                r++;
                ncnt[arr[r]]++;
                if(ncnt[arr[r]] > cntOverlap)
                    cntOverlap = ncnt[arr[r]];

                if(cntOverlap <= K)
                    ans = Math.max(ans, r-l+1);
            }
        }

        System.out.println(ans);
    }
}
profile
게임개발자 백엔드개발자

0개의 댓글