이미 용액들이 오름차순으로 정렬되어 있으므로, 양 끝에 포인터를 둬서 경우에 따라 안쪽으로 포인터를 좁혀가며 혼합 용액의 값을 갱신한다.
특성값이 0에 가깝다는 말은, 특성값의 절대값이 최소인 값을 찾는다는 것이다.
초기에는 절댓값의 최솟값을 큰 값(Integer.MAX_VALUE)으로 설정해 놓고, 더 작은 값이 나올 때마다 갱신한다.
투포인터 이동전략
두 용액의 합을 기준으로 판단한다.
package BOJ;
import java.io.*;
import java.util.*;
public class sol2467 {
static int n;
static int[] arr;
static int resultLeft, resultRight;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int left = 0;
int right = n - 1;
int val = Integer.MAX_VALUE;
while (left < right) {
int mixed = Math.abs(arr[left] + arr[right]);
if (mixed < val) {
val = mixed;
resultLeft = left;
resultRight = right;
} else {
if (arr[left] + arr[right] < 0) {
left++;
} else {
right--;
}
}
}
System.out.println(arr[resultLeft] + " " + arr[resultRight]);
}
}