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.util.*;
import java.io.*;
public class Main {
public static int N;
public static int arr[];
public static int selected[];
public static boolean[] visited;
public static int result = Integer.MIN_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
arr = new int[N];
selected = new int[N];
visited = new boolean[N];
for(int i=0; i<N; i++)
arr[i] = Integer.parseInt(st.nextToken());
DFS(0);
System.out.println(result);
}
public static void DFS(int count) {
if(count == N) {
result = Math.max(Calculate(), result);
return;
}
for(int i=0; i<N; i++) {
if(!visited[i]) {
visited[i] = true;
selected[count] = arr[i];
DFS(count+1);
visited[i] = false;
}
}
}
public static int Calculate() {
int sum = 0;
for(int i=0; i<N-1; i++)
sum += Math.abs(selected[i] - selected[i+1]);
return sum;
}
}
DFS를 활용하여 문제를 해결한다. visited배열을 활용하여 중복 여부도 확인해준다. 절댓값의 경우 Math.abs() 함수를 활용한다.