스터디/Algorithm

[백준] 겹치는 건 싫어 java - two pointer

혜유우 2024. 5. 2. 16:50

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

출력

조건을 만족하는 최장 연속 부분 수열의 길이를 출력한다.

예제 입력 1 복사

9 2
3 2 5 5 6 4 4 5 7

예제 출력 1 복사

7

예제 입력 2 복사

10 1
1 2 3 4 5 6 6 7 8 9

예제 출력 2 복사

6

 

 

내 풀이

hashMap과 투 포인터로 풀었다

hashMap에 배열 값을 0으로 초기화 해준 후

K초과 일 때에 start_index를 증가시키는 방향으로 로직을 짰다

 

 

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

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[] arr = new int[N];

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

        int start_index=0, end_index=0;
        HashMap<Integer, Integer> sameMap = new HashMap<>();
        for(int i=0;i<N;i++){
            sameMap.put(arr[i],0);
        }

        int length = Integer.MIN_VALUE;
        while(start_index<N && end_index<N){
            if(sameMap.get(arr[end_index])>=K) {
                sameMap.put(arr[start_index], sameMap.get(arr[start_index])-1);
                start_index++;
            }else{
                sameMap.put(arr[end_index], sameMap.get(arr[end_index])+1);
                end_index++;
            }
            length = Math.max(length, end_index-start_index);
        }
        System.out.println(length);
    }
}