N개의 정수로 이루어진 배열 A가 주어진다. 이때, 배열에 들어있는 정수의 순서를 적절히 바꿔서 다음 식의 최댓값을 구하는 프로그램을 작성하시오.
첫째 줄에 N (3 ≤ N ≤ 8)이 주어진다. 둘째 줄에는 배열 A에 들어있는 정수가 주어진다. 배열에 들어있는 정수는 -100보다 크거나 같고, 100보다 작거나 같다.
첫째 줄에 배열에 들어있는 수의 순서를 적절히 바꿔서 얻을 수 있는 식의 최댓값을 출력한다.
import java.util.*;
public class Main {
static int N, max=0;
static int[] arr, list;
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
arr = new int[N];
list = new int[N];
visited = new boolean[N];
for (int i = 0; i < N; i++)
arr[i] = sc.nextInt();
BT(0);
System.out.println(max);
}
public static void BT(int depth) {
if (depth == N) {
max = Math.max(max, calcul());
return;
}
for (int i = 0; i < N; i++) {
if (visited[i])
continue;
visited[i] = true;
list[depth] = arr[i];
BT(depth+1);
visited[i] = false;
}
}
public static int calcul() {
int result = 0;
for (int i = 0; i < N-1; i++) {
result += Math.abs(list[i]-list[i+1]);
}
return result;
}
}