본문 바로가기
알고리즘/기타

[백준 20922번] 겹치는 건 싫어 (JAVA)

by 그릿er 2021. 6. 11.

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

 

20922번: 겹치는 건 싫어

홍대병에 걸린 도현이는 겹치는 것을 매우 싫어한다. 특히 수열에서 같은 원소가 여러 개 들어 있는 수열을 싫어한다. 도현이를 위해 같은 원소가 $K$개 이하로 들어 있는 최장 연속 부분 수열

www.acmicpc.net

 

 

 

해당 문제는 투 포인터를 활용한 문제이다.

 

100,000 크기의 배열을 만들어서 중복되는 숫자를 세면서 startIdx 와 endIdx를 움직였다.

endIdx를 중심으로 움직이되, 중복 되는 숫자가 k를 넘는 것을 limit 함수의 원소를 통해 확인하여 startIdx를 움직였다.

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
 
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        
        int N = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        
        int[] limit = new int[100001];
        int[] num = new int[N];
        
        st = new StringTokenizer(br.readLine()," ");
        for(int i=0; i<N; i++) {
            num[i] = Integer.parseInt(st.nextToken());
        }
        //입력 끝
        
        int max = 0;
        int startIdx = 0;
        int endIdx = 0;
        limit[num[startIdx]]++;
        
        for(int i=1; i<N; i++) {
            if(limit[num[i]]<k) {
                endIdx = i;
                limit[num[endIdx]]++;
                max = Math.max(endIdx-startIdx+1, max);
            }else {
                while(true) {
                    if(num[startIdx] == num[i]) {
                        startIdx++;
                        endIdx = i;
                        break;
                    }else {
                        limit[num[startIdx]]--;
                        startIdx++;
                    }
                }
            }
        }
        System.out.println(max);
    }
}
cs