1. 1보다 큰 양수는 큰 수 부터 2개씩 짝을 지어 곱한다.
→ 곱하지 못하고 남은 양수는 더한다.
2. 1은 그대로 더하는데 사용한다.
3. 음수는 작은 수 부터 2개씩 짝을 지어 곱해서 양수로 만든다.
→ 곱하지 못하고 남은 음수는 0과 곱해서 0으로 만들거나 0이 없으면 그대로 더한다.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
ArrayList<Integer> posNum = new ArrayList<>(); // 양수 저장
ArrayList<Integer> negNum = new ArrayList<>(); // 음수 저장
int ones = 0; // 1의 수
int zeros = 0; // 0의 수
int posIdx = 0;
int negIdx = 0;
int sum = 0;
for(int i=0; i<N; i++) {
int n = Integer.parseInt(br.readLine());
if(n<0) {
negNum.add(n);
}
else if(n == 0) {
zeros++;
}
else if(n == 1) {
ones++;
}
else {
posNum.add(n);
}
}
//양수 계산
Collections.sort(posNum, Comparator.reverseOrder());
while(posIdx+1 <= posNum.size()-1) {
int n1 = posNum.get(posIdx);
int n2 = posNum.get(posIdx+1);
sum += n1*n2;
posIdx += 2;
}
if(posIdx == posNum.size()-1) {
sum += posNum.get(posIdx);
}
//음수 계산
Collections.sort(negNum);
while(negIdx+1 <= negNum.size()-1) {
int n1 = negNum.get(negIdx);
int n2 = negNum.get(negIdx+1);
sum += n1*n2;
negIdx += 2;
}
if(zeros == 0) {
if(negIdx == negNum.size()-1) {
sum += negNum.get(negIdx);
}
}
//1 계산
sum += ones;
System.out.print(sum);
}
}
반응형
'CS > 알고리즘' 카테고리의 다른 글
백준 9251번 : LCS[java] (0) | 2023.02.22 |
---|---|
백준 17136번 : 색종이 붙이기[java] (1) | 2023.02.21 |
백준 11437번 : LCA[java] (0) | 2023.02.15 |
백준 16236번 : 아기 상어[java] (0) | 2023.02.13 |
백준 11066번 : 파일합치기[java] (0) | 2023.02.10 |
댓글