ALGORITHM
[JAVA] 백준 2798번 - 블랙잭
연듀
2022. 9. 13. 15:30
https://www.acmicpc.net/problem/2798
2798번: 블랙잭
첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장
www.acmicpc.net
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[] arr= new int[n];
int max = Integer.MIN_VALUE;
st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
for(int i=0; i<n-2; i++){
for(int j=i+1; j<n-1; j++){
for(int k=j+1; k<n; k++){
int sum = arr[i]+arr[j]+arr[k];
if(sum <= m){
max = Math.max(max, sum);
}
}
}
}
System.out.println(max);
}
}
브루트포스 알고리즘이다. 모든 경우의 수를 탐색하면서 요구조건에 충족되는 결과만을 가져온다.
3중 for문을 돌며 카드 3개를 뽑는 경우의 수를 모두 탐색해 합이 m보다 작으면서 최대일때의 경우를 찾는다.
반응형