[Java] 백준 2230 수 고르기

hyunnzl·2025년 5월 7일

백준

목록 보기
81/116
post-thumbnail

https://www.acmicpc.net/problem/2230

난이도

골드5

문제

N개의 정수로 이루어진 수열 A[1], A[2], …, A[N]이 있다. 이 수열에서 두 수를 골랐을 때(같은 수일 수도 있다), 그 차이가 M 이상이면서 제일 작은 경우를 구하는 프로그램을 작성하시오.

예를 들어 수열이 {1, 2, 3, 4, 5}라고 하자. 만약 M = 3일 경우, 1 4, 1 5, 2 5를 골랐을 때 그 차이가 M 이상이 된다. 이 중에서 차이가 가장 작은 경우는 1 4나 2 5를 골랐을 때의 3이 된다.

입력

첫째 줄에 두 정수 N, M이 주어진다. 다음 N개의 줄에는 차례로 A[1], A[2], …, A[N]이 주어진다.

출력

첫째 줄에 M 이상이면서 가장 작은 차이를 출력한다. 항상 차이가 M이상인 두 수를 고를 수 있다.

내 코드

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

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] strings = br.readLine().split(" ");
		int N = Integer.parseInt(strings[0]);
		int M = Integer.parseInt(strings[1]);

		int[] nums = new int[N];
		for (int i = 0; i < N; i++) {
			nums[i] = Integer.parseInt(br.readLine());
		}

		Arrays.sort(nums);

		int left = 0;
		int right = 0;
		int ans = Integer.MAX_VALUE;

		while (right < N) {
			int val = nums[right] - nums[left];
			if (val < M) {
				right++;
			} else {
				left++;
				ans = Math.min(ans, val);
			}

			if (left == right) {
				if (right < N) {
					right++;
				}
			}
		}

		System.out.println(ans);
	}
}

0개의 댓글