알고리즘

[Java] 백준 2230번 수 고르기

J3SUNG 2023. 8. 9. 00:55
728x90

투 포인터 문제입니다.

두 값의 차의 절댓값이 M이상이면서 가장 작은 값을 찾아야합니다.
같은 수를 고를수도 있습니다.

left와 right를 0으로 둡니다.
해당 위치의 값들의 차이를 구합니다.

1. m보다 작은 경우
- right 증가

2. m보다 큰 경우
- left 증가
- 결과값보다 작으면 갱신

3. m과 같은 경우
- left, right 증가
- 결과값보다 작으면 갱신

import java.util.*;
import java.io.*;

public class Main {
  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());

    int n = Integer.parseInt(st.nextToken());
    int m = Integer.parseInt(st.nextToken());
    int[] arr = new int[n];
    int result = 2_000_000_001;

    for (int i = 0; i < n; ++i) {
      arr[i] = Integer.parseInt(br.readLine());
    }

    Arrays.sort(arr);

    int left = 0;
    int right = 0;
    while (left <= right && right < n) {
      int num = Math.abs(arr[left] - arr[right]);
      if (num < m) {
        ++right;
      } else if (num > m) {
        result = Math.min(result, num);
        ++left;
      } else {
        result = Math.min(result, num);
        ++right;
        ++left;
      }
    }

    bw.write(result + "\n");
    bw.close();
  }
}