본문 바로가기

알고리즘/초급1

[JAVA] 백준 10819번: 차이를 최대로 ( 초급 2-23 ) - hard

문제

N개의 정수로 이루어진 배열 A가 주어진다. 이때, 배열에 들어있는 정수의 순서를 적절히 바꿔서 다음 식의 최댓값을 구하는 프로그램을 작성하시오.

|A[0] - A[1]| + |A[1] - A[2]| + ... + |A[N-2] - A[N-1]|

입력

첫째 줄에 N (3 ≤ N ≤ 8)이 주어진다. 둘째 줄에는 배열 A에 들어있는 정수가 주어진다. 배열에 들어있는 정수는 -100보다 크거나 같고, 100보다 작거나 같다.

출력

첫째 줄에 배열에 들어있는 수의 순서를 적절히 바꿔서 얻을 수 있는 식의 최댓값을 출력한다.

 

문제 해결

모든 경우의 수를 계산해본다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class baekjoon10819 {
    private static int n;
    private static int[] info;
    private static int[] res;
    private static boolean[] visit;
    private static int result = 0;

    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        info = new int[n];
        res = new int[n];
        visit = new boolean[n];

        StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            info[i] = Integer.parseInt(st.nextToken());
        }
        allPermutation10819(0);
        System.out.println(result);
    }

    private static void allPermutation10819(int index) {
        if (index == n) {
            // toDo : calculate result
            int tempResult = 0;
            int first = res[0];
            for (int i = 1; i < n; i++) {
                int second = res[i];
                tempResult += Math.abs(second - first);
                first = second;
            }
            if (tempResult > result) {
                result = tempResult;
            }
            return;
        }

        for (int i = 0; i < n; i++) {
            if (!visit[i]) {
                visit[i] = true;
                res[index] = info[i];
                allPermutation10819(index + 1);
                visit[i] = false;
            }

        }

    }
}