https://www.acmicpc.net/problem/20922
20922번: 겹치는 건 싫어
홍대병에 걸린 도현이는 겹치는 것을 매우 싫어한다. 특히 수열에서 같은 원소가 여러 개 들어 있는 수열을 싫어한다. 도현이를 위해 같은 원소가 $K$개 이하로 들어 있는 최장 연속 부분 수열
www.acmicpc.net
저는 투 포인트를 이용해 문제를 해결하였습니다.
일단 엔드 포인트를 옮기면서 현재 값의 cnt를 늘립니다. 이 값이 k보다 크다면 이 값이 k보다 같거나 작아질 때 까지 시작 포인트를 늘리면서 해당하는 값의 cnt를 줄여나갑니다.
package BOJ.twopoint;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_20922_2 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Function<String,Integer> stoi = Integer::parseInt;
StringTokenizer st = new StringTokenizer(br.readLine());
int n = stoi.apply(st.nextToken());
int k = stoi.apply(st.nextToken());
int[] input = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++){
input[i] = stoi.apply(st.nextToken());
}
int result = cal(input,n,k);
System.out.println(result);
}
private static final int MAX_VALUE = 100_000;
private static int cal(int[] input, int n, int k) {
int[] cnt = new int[MAX_VALUE + 1];
int si = 0;
int ei = 0;
int result = 0;
while(true){
if(ei == n){
break;
}
int now = input[ei++];
cnt[now]++;
while(cnt[now] > k){
cnt[input[si++]]--;
}
result = Math.max(result, ei - si);
}
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 13904번 과제 (JAVA) (0) | 2023.07.10 |
---|---|
백준 1700번 멀티탭 스케줄링 (JAVA) (0) | 2023.07.09 |
백준 2579번 계단 오르기 (JAVA) (0) | 2023.07.07 |
백준 1806번 부분합 (JAVA) (0) | 2023.07.06 |
백준 14235번 크리스마스 선물 (JAVA) (0) | 2023.07.05 |