본문 바로가기
자료구조&알고리즘/완전 탐색 (브루트 포스)

[백준] 순열 - 10819번 차이를 최대로 (Java)

by _din 2022. 2. 21.

문제링크

 

10819번: 차이를 최대로

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

www.acmicpc.net

 

접근한 방법

  • 순열

 


풀이방법

https://doongjeol.tistory.com/136 참조

 


소스코드

import java.io.*;
import java.util.StringTokenizer;

public class Q_10819_MaxDiff {
    public static int[] data;
    public static int result;
    public static void permutation(int[] arr, int n, int r, boolean[] selected, int depth){
        if(depth == r){
            int sum = 0;
            for(int i=0 ; i <arr.length-1 ; i++){
                sum += Math.abs(arr[i] - arr[i+1]);

            }
            result = Math.max(sum, result);
            return;
        }

        for(int i=0 ; i<arr.length ; i++){
            if(selected[i]){
                continue;
            }
            arr[depth] = data[i];

            selected[i] = true;
            permutation(arr, n, r, selected, depth+1);
            selected[i] = false;
        }

    }


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

        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());

        data = new int[n];
        for (int i = 0; i < n; i++) {
            data[i] = Integer.parseInt(st.nextToken());
        }

        permutation(new int[n], n, n, new boolean[n], 0);
        bw.write(result+"");

        br.close();
        bw.close();
    }
}
반응형

댓글