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);
}
}
'스터디 > Algorithm' 카테고리의 다른 글
[백준] 불 4179 java - bfs (0) | 2024.05.03 |
---|---|
[프로그래머스스쿨] 가장 큰 수 java (lv.2) (0) | 2024.05.03 |
[백준] 배열 합치기 java - two pointer (1) | 2024.04.29 |
[백준] 폴리오미노 java - greedy (0) | 2024.04.17 |
[프로그래머스] 완주하지 못한 선수 java (lv. 1) (0) | 2024.04.11 |