N개의 정수로 이루어진 배열 A가 주어진다. 이때, 배열에 들어있는 정수의 순서를 적절히 바꿔서 다음 식의 최댓값을 구하는 프로그램을 작성하시오.
|A[0] - A[1]| + |A[1] - A[2]| + ... + |A[N-2] - A[N-1]|
순열의 문제이다.
순열은 재귀를 통해 풀 수 있다.
1, 2, 3의 숫자가 있을 때
1의 숫자부터 반복문을 시작하고, 숫자를 하나 고른 후 재귀를 통해 다시 이 반복문에 도달한다.
만약 현재 숫자를 이전에 골랐다면 선택하지 못한다.
1 2 3 -> 1 3 2 -> 2 1 3 -> 2 3 1 -> 3 1 2 -> 3 2 1의 순서로 숫자를 선택하게 된다.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n, ans;
vector<int>v;
int save[8];
bool check[8];
void input() {
for (int i = 0; i < n; i++) {
int num;
cin >> num;
v.push_back(num);
}
}
void calAns() {
int cur_ans = 0;
for (int i = 0; i < n-1; i++) {
cur_ans += abs(save[i] - save[i + 1]);
}
ans = max(ans, cur_ans);
}
void func(int depth) {
if (depth == n) {
calAns();
}
for (int i = 0; i < n; i++) {
if (!check[i]) {
check[i] = true;
save[depth] = v[i];
func(depth + 1);
check[i] = false;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
input();
func(0);
cout << ans;
return 0;
}