알고리즘

<백준> 14888번 자바 알고리즘

changha. 2022. 1. 2. 22:33
import java.util.*;

public class Main
{   
    static int MAX = Integer.MIN_VALUE;
    static int MIN = Integer.MAX_VALUE;
    static int[] numbers, operator;
    static int N;
    
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		N = input.nextInt();
		numbers = new int[N];
		operator = new int[4];
		
		for(int i=0; i < N; i++){
		    numbers[i] = input.nextInt();
		}
		for (int i = 0; i < 4; i++) {
			operator[i] = input.nextInt();
		}
		
		BackTracking(numbers[0], 1);
		
		System.out.println(MAX);
		System.out.println(MIN);
		
	}
	
	private static void BackTracking(int num, int idx){
	    
	    if(idx == N){
	        MAX = Math.max(MAX, num);
	        MIN = Math.min(MIN, num);
	        return;
	    }
	    
	    for(int i=0; i < 4; i++){
	        
	        if(operator[i] > 0){
	            // 연산자 갯수 1만큼 감소
	            operator[i]--;
	            
	            switch (i){
	                case 0: BackTracking(num + numbers[idx], idx + 1);  break;
	                case 1: BackTracking(num - numbers[idx], idx + 1);  break;
	                case 2: BackTracking(num * numbers[idx], idx + 1);  break;
	                case 3: BackTracking(num / numbers[idx], idx + 1);  break;
	                
	            }
	            
	            operator[i]++;
	                
	        }
	    }
	}
}