알고리즘/백준
백준 22857 - 가장 긴 짝수 연속한 부분 수열(small)
dev.moon
2022. 4. 5. 23:05
https://www.acmicpc.net/problem/22857
1. 유형
- 투포인터
2. 풀이
- 투포인터 변수 R, L을 잡는다. 시작 인덱스는 0번
- R, L의 사이에 홀수의 갯수가 K개 초과면 L증가, 반대는 R증가
3. 코드
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 =stoi(st.nextToken());
int K = stoi(st.nextToken());
int arr[] = new int[N];
st = new StringTokenizer(br.readLine());
for(int i=0; i<N; i++) {
arr[i] = stoi(st.nextToken());
}
int R=0,L=0;
int odd=0;
int even=0;
if(arr[0]%2==0) even++;
else odd++;
int answer = even;
while(R>=L) {
if(odd>K) {
if(arr[L]%2==0) even--;
else odd--;
L++;
}else {
R++;
if(R>=N) break;
if(arr[R]%2==0) even++;
else odd++;
answer = Math.max(answer, even);
}
}
System.out.println(answer);
}
static int stoi(String s) {
return Integer.valueOf(s);
}
}