728x90
반응형
문제 설명
1. N이 주어진다.
2. N개의 배열에 해당하는 -1000000000~1000000000까지 범위의 용액들이 주어진다.
3. 용액을 섞었을 합의 절대값이 0에 가장 가까운 값을 return하면 된다.
풀이 과정
1. 이분 탐색 문제이다.
2. 배열 정렬 후, 최대+최소를 구해서 이게 0보다 크면 최대값을 줄이고 0보다 작으면 최소값을 키운다.
3. 그리고 구할 때 마다 정답을 바꾸어 주면 된다. (범위가 -1000000000~1000000000니까 최대값은 2000000000)
ex) -2 4 -99 -1 98 이렇게이면
정렬 -> -99, -2, -1, 4, 98
합 -> (-99+98) = -1 [정답 변경!]
0보다 작음 -> (-2+98) = 96 [정답 그대로]
0보다 큼 -> (-2+4) = 2 [정답 그대로]
0보다 작음 -> (-1+4) = 3 [정답 그대로]
.....
4. 풀이 과정만 생각해 내면 간단히 구할 수 있는 문제이다.
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Main { | |
public static int solution[]; | |
public static int ans=2000000000; | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int N = sc.nextInt(); | |
solution = new int[N]; | |
for(int i=0; i<N; i++) solution[i] = sc.nextInt(); | |
Arrays.sort(solution); | |
int start = 0; | |
int end = solution.length-1; | |
int ans1 = solution[start]; | |
int ans2 = solution[end]; | |
while(start < end){ | |
int combine = (solution[start]+solution[end]); | |
if(Math.abs(ans) > Math.abs(combine)){ // 현재 답보다 구한 값의 절대값이 작은 경우 | |
ans = combine; // 답 변경 후 해당 위치 저장 | |
ans1 = solution[start]; | |
ans2 = solution[end]; | |
} | |
if(combine<0){ // 0보다 작으면 작은 값을 키워주고 | |
start += 1; | |
}else{ // 0보다 크면 큰 값을 작게 만들어주기~ | |
end -= 1; | |
} | |
} | |
System.out.printf("%d %d", ans1, ans2); | |
} | |
} |
반응형
'알고리즘 공부' 카테고리의 다른 글
[백준 1764번] 듣보잡 - java (0) | 2021.10.04 |
---|---|
[백준 12015번] 가장 긴 증가하는 부분 수열2 - java (0) | 2021.09.26 |
[백준 1780번] 종이의 개수- java (0) | 2021.09.22 |
[백준 1992번] 쿼드트리- java (0) | 2021.09.21 |
[백준 1057번] 오르막 수- java (0) | 2021.09.20 |