[백준] 10819번 : 차이를 최대로 - JAVA [자바]

가오리·2023년 12월 2일
0
post-thumbnail

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


DFS 문제이다.

  1. 입력 받은 수로 중복 없이 순열을 만든다.
  2. 만들어진 순열마다 |A[0] - A[1]| + |A[1] - A[2]| + ... + |A[N-2] - A[N-1]| 를 하여 가장 최대의 값을 구한다.

public class bj10819 {

    public static int MAX;
    public static int N;
    public static boolean[] visited;
    public static int[] numArr;
    public static int[] answerArr;
    public static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws Exception {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        N = Integer.parseInt(br.readLine());
        numArr = new int[N];
        answerArr = new int[N];
        visited = new boolean[N];
        String line = br.readLine();
        String[] split = line.split(" ");
        for (int i = 0; i < N; i++) {
            numArr[i] = Integer.parseInt(split[i]);
        }

        dfs(0);

        bw.write(MAX + "");

        bw.flush();
        bw.close();
        br.close();
    }

    private static void dfs(int depth) {
        if (depth == N) {
            int count = 0;
            for (int i = 0; i < N - 1; i++) {
                count = count + Math.abs(answerArr[i] - answerArr[i + 1]);
            }
            MAX = Math.max(count, MAX);
            return;
        }
        for (int i = 0; i < N; i++) {
            if (!visited[i]) {
                visited[i] = true;
                answerArr[depth] = numArr[i];
                dfs(depth + 1);
                visited[i] = false;
            }
        }
    }
}
profile
가오리의 개발 이야기

0개의 댓글

관련 채용 정보