본문 바로가기

코딩테스트/JAVA

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

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

 

dfs를 이용해서 하나하나 다 계산해주는 방법을 사용했다. 

 

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

public class Main {
	public static int[] a, arr;
	public static int n, Max = -1;
	public static boolean[] visit;
	public static StringBuilder sb = new StringBuilder();

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		
		
		n = sc.nextInt();
		a = new int[n];
		arr= new int[n];
		visit = new boolean[n];
		
		for(int i = 0; i< n;i++) {
			a[i] = sc.nextInt();
		}
		
		dfs(0);
		
		sb.append(Max);
		
		System.out.println(sb);
	}

	public static void dfs(int depth) {
		if (depth == n) {
			int cnt = 0;
			for(int i =1;i<n;i++) {
				cnt += Math.abs(arr[i- 1]-arr[i]);
			}
			
			if(cnt > Max)
				Max = cnt;
			
			return;
		}
		
		for(int i=0;i<n;i++) {
			if(!visit[i]) {
				visit[i] = true;
				arr[depth] = a[i];
				dfs(depth + 1);
				visit[i] = false;
			}
		}
	}
}