자바로 백준 1337 풀기

hong030·2023년 4월 12일
0
  • 실버 4단계 문제

풀이)

한 배열 내에 적어도 원소가 5개 이상 연속되는 올바른 배열이 되게 하기 위해, 배열에 추가해야 할 최소한의 원소 개수를 구하여라.

하나의 원소에 대해, 배열에 원소, 원소+1, 원소+2, 원소+3, 원소+4 값이 각각 존재하는지를 체크하면 된다.

내 코드)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class Backjoon1337 {
	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		
		//1. 입력
		int N = Integer.parseInt(bf.readLine());
		ArrayList<Integer> list = new ArrayList<>();
		for(int i=0;i<N;i++) {
			list.add(Integer.parseInt(bf.readLine()));
		}
		
		//2. 정렬
		Collections.sort(list);
		
		//3. 확인
		ArrayList<Integer> max = new ArrayList<>();
		for(int i=0;i<N;i++) {
			int count = 0;
			if(list.contains(list.get(i)))count++;
			if(list.contains(list.get(i)+1))count++;
			if(list.contains(list.get(i)+2))count++;
			if(list.contains(list.get(i)+3))count++;
			if(list.contains(list.get(i)+4))count++;
			max.add(count);
		}
        Collections.sort(max, Collections.reverseOrder());
        System.out.println(5-max.get(0));
	}
}

profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글