백준 2531 - 회전 초밥 (java)

Mendel·2024년 5월 12일

알고리즘

목록 보기
44/85

문제 접근

문제는 매우 심플하게 투 포인터다.
투 포인터로 한칸씩 슬라이드 해가면서, 중복을 제거한 가짓수를 카운트해주면 된다.

문제 풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class Main {
    static int maxN;
    static int n;
    static int[] counter;
    static int[] numbers;
    static int N, d, k, c;

    static public void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        d = Integer.parseInt(st.nextToken());
        k = Integer.parseInt(st.nextToken());
        c = Integer.parseInt(st.nextToken());

        counter = new int[d + 1];
        Arrays.fill(counter, 0);

        numbers = new int[N];
        for (int i = 0; i < N; i++) {
            numbers[i] = Integer.parseInt(br.readLine());
            if (i < k) slide(0, numbers[i]);
        }

        for (int i = 1; i < N; i++) {
            slide(numbers[(i - 1) % N], numbers[(i + k - 1) % N]);
        }

        System.out.println(maxN);
    }

    static void slide(int outN, int inN) {
        if (counter[inN] == 0) n++;
        counter[inN]++;

        if (counter[outN] == 1) n--;
        counter[outN]--;

        if (counter[c] == 0) {
            maxN = Math.max(maxN, n + 1);
        } else {
            maxN = Math.max(maxN, n);
        }
    }
}

profile
이것저것(안드로이드, 백엔드, AI, 인프라 등) 공부합니다

0개의 댓글