[백준 1744] 수 묶기 (JAVA)

solser12·2021년 11월 27일
0

Algorithm

목록 보기
43/56

문제


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

풀이


정렬 후 여러 조건들을 고려하여 구현하시면 됩니다.

  1. 가장 작은 음수끼리 곱해야한다.
    [-5, -4, -3, -2] => (-5*-4)+(-3*-2)

  2. 음수 갯수가 홀수이면 0이 있는지 확인
    [-5, -4, -2] => (-5*-4)-2
    [-5, -4, -2, 0] => (-5*-4)*(-2*0)

  3. 가장 큰 양수끼리 곱해야한다.
    [5, 4, 3, 2] => (5*4)+(3*2)

  4. 1은 곱하지말고 더해야한다.
    [5, 4, 2, 1] => (5*4)+2+1

코드


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));

        final int EMPTY = Integer.MAX_VALUE;
        int N = Integer.parseInt(br.readLine());

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

        int ans = 0, leftIndex = 0, temp = EMPTY;
        while (leftIndex < N && arr[leftIndex] <= 0) {
            if (temp == EMPTY) {
                temp = arr[leftIndex];
            } else {
                ans += temp * arr[leftIndex];
                temp = EMPTY;
            }
            leftIndex++;
        }

        if (temp != EMPTY) {
            ans += temp;
            temp = EMPTY;
        }

        int rightIndex = N - 1;
        while (rightIndex >= leftIndex) {
            if (temp == EMPTY) {
                temp = arr[rightIndex];
            } else {
                if (arr[rightIndex] == 1) {
                    ans += temp + arr[rightIndex];
                } else {
                    ans += temp * arr[rightIndex];
                }
                temp = EMPTY;
            }
            rightIndex--;
        }

        if (temp != EMPTY) {
            ans += temp;
        }

        System.out.println(ans);
        br.close();
    }
}
profile
더 나은 방법을 생각하고 고민합니다.

0개의 댓글