본문 바로가기

Algorithm/Baekjoon

[백준_JAVA_알고리즘] 2798 블랙잭

import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int M = scanner.nextInt();
        int sum = 0; int tmp = 0;
        int[] arr = new int[N];
        
        if(N >=3 && N <= 100 && M >= 10 && M <= 300000) {
        	// 카드에 들어가는 숫자
            for(int i = 0; i < N; i++) {
            	arr[i] = scanner.nextInt();
            }
            
            for(int i = 0; i < N; i++) {
            	for(int j = i+1; j < N; j++) {
            		for(int k = j+1; k < N; k++) {
            			sum = arr[i]+arr[j]+arr[k];
            			if(sum > tmp && sum <= M)
            				tmp = sum;
            		}
            	}
            }
            System.out.println(tmp);
        	
        }else {
        	System.out.println("N의 범위 (3 ≤ N ≤ 100)로 인한 시스템 종료");
        	System.exit(0);
        }
        scanner.close();
    }
}

 

브루트 포스 알고리즘을 사용했다.

반복문과 조건문을 조합하여 전체 경우의 수를 탐색하는 알고리즘이다.