22862번: 가장 긴 짝수 연속한 부분 수열 (large)
수열 $S$에서 최대 $K$번 원소를 삭제한 수열에서 짝수로 이루어져 있는 연속한 부분 수열 중 가장 긴 길이를 출력한다.
www.acmicpc.net
의식의 흐름
투 포인터를 사용해서 가장 긴 길이를 저장해두자
풀이 과정
1. 수열의 길이(N), 삭제할 수 있는 최대 횟수(K)를 입력받는다.
2. N개의 숫자를 배열(nums)에 담아둔다.
3. 삭제한 횟수(removedCnt)가 K 이하인 경우 최대 길이(maxLength)를 갱신한다.
3-1) start, end 포인터를 둔다.
3-2) removedCnt에 따라 start, end를 이동한다.
- removedCnt <= K인 경우, nums[end]의 값에 따라 removedCnt를 증가시키고 maxLength를 갱신한 후 end를 이동한다.
- removedCnt > K인 경우, nums[start]의 값에 따라 removedCnt를 감소시키고 start를 이동한다.
4. maxLength를 출력한다.
코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
public static int N, K;
public static int[] nums;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
nums = new int[N];
for(int i=0;i<N;i++){
nums[i] = Integer.parseInt(st.nextToken());
}
int start = 0;
int end = 0;
int removedCnt = 0;
int maxLength = 0;
while(end<N){
if(removedCnt<=K){
if(nums[end]%2 == 1){
removedCnt++;
}
if(removedCnt > K){
end++;
continue;
}
maxLength = Math.max(maxLength, end-start+1-removedCnt);
end++;
}
else{
if(nums[start]%2 == 1){
removedCnt--;
}
start++;
}
}
bw.write(Integer.toString(maxLength));
bw.flush();
br.close();
bw.close();
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[JAVA] 백준 q16926 - 배열 돌리기 1 (0) | 2023.11.21 |
---|---|
[JAVA] 백준 q22945 - 팀 빌딩 (2) | 2023.11.20 |
[JAVA] 백준 q20922 - 겹치는 건 싫어 (2) | 2023.10.30 |
백준 q14567 - 선수과목 (Prerequisite) (0) | 2023.10.27 |
[JAVA] 백준 q2631 - 줄세우기 (2) | 2023.10.26 |