백준 2531번 회전 초밥 Java

: ) YOUNG·2024년 3월 25일
1

알고리즘

목록 보기
339/411
post-thumbnail

백준 2531번
https://www.acmicpc.net/problem/2531

문제



생각하기


✔️



동작



결과


코드



import java.io.*;
import java.util.StringTokenizer;

public class Main {

    // input
    private static BufferedReader br;

    // variables
    private static int N, D, K, C;
    private static int[] arr;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        input();

        bw.write(solve());
        bw.close();
    } // End of main()

    private static String solve() {
        StringBuilder sb = new StringBuilder();

        int[] set = new int[D + 1];
        int start = 0;
        int end = K - 1;
        int max = -1;
        int count = 0;

        for (int i = start; i <= end; i++) {
            set[arr[i]]++;
            if (set[arr[i]] == 1) {
                count++;
            }
        }

        if (set[C] == 0) {
            max = count + 1;
        } else {
            max = count;
        }

        while (start < N) {
            set[arr[start]]--;
            if (set[arr[start]] == 0) {
                count--;
            }

            start++;
            end++;
            end = end % N;

            set[arr[end]]++;
            if (set[arr[end]] == 1) {
                count++;
            }

            int temp = count;
            if (set[C] == 0) {
                temp++;
            }

            if (temp > max) {
                max = temp;
            }
        }


        sb.append(max);
        return sb.toString();
    } // End of solve()

    private static void input() throws IOException {
        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());

        arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(br.readLine());
        }
    } // End of input()
} // End of Main class


0개의 댓글