boj 20922

임종혁·2024년 1월 21일

문제 해결

  1. 배열이 100 000 개 올수 있으니 그만한 배열 크기로 선어 ㄴ
  2. start end 지정
  3. 만약 check[arr[end]] 가 m 보다 작을 때 check[arr[end]] + 1 end +1 count 올리기
  4. ccount max 비교
  5. 만약 arr[end] 가 m 보다 클때 check[arr[start]] -1 start ++ // 처음 위치 줄이기
  6. 만약 end가 끝까지 가면 종료

arr =new int [100001] //1. 
//2.
start = 0 
end = 0

 while(start <= n){
            //3.
            if(check[arr[end]] < k){
                check[arr[end]] +=1;
                end++;
                //4.
                int length = end-start-1;
                if(length > max){
                    max = length;
                }
//5
            } else if (check[arr[end]] >= k) {
                check[arr[start]] -=1;
                start ++;
            }
            //6.
            if(end == n){
            break;
            }
        }

전체 코드

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

        StringTokenizer st;

        st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());

        int[] arr = new int[n];
        int[] check = new int[100001];

        st = new StringTokenizer(br.readLine());
        for(int i=0; i<arr.length; i++){
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int start = 0;
        int end = 0;
        int max = 0;

        while(start <= n){




            //3.
            if(check[arr[end]] < k){
                check[arr[end]] +=1;
                end++;
                //4.
                int length = end-start-1;
                if(length > max){
                    max = length;
                }
//5
            } else if (check[arr[end]] >= k) {
                check[arr[start]] -=1;
                start ++;
            }
            //6.
            if(end == n){
            break;
            }
        }
        if(n== 0){
            System.out.println(0);
        }else{
            System.out.println(max+1);
        }
    }

왜이리 투포인터 문제는 조건이 까다로운거 같지??

0개의 댓글