hye-log

[백준]2798번 블랙잭(JAVA) 본문

CodingTest/Baekjoon

[백준]2798번 블랙잭(JAVA)

iihye_ 2023. 7. 29. 17:56

0. 문제 링크

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

 

2798번: 블랙잭

첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장

www.acmicpc.net

 

1. 문제 설명

1) N 장의 카드 중에서 M 을 넘지 않으면서 M에 최대한 가까운 카드 3장의 합 구하기

 

2. 입출력

// input
5 21
5 6 7 8 9

// output
21

 

3. 코드

import java.util.*;

public class b2798 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int N = sc.nextInt(); // 카드의 개수
		int M = sc.nextInt(); // 카드의 합
		int[] cards = new int[N]; // 카드의 숫자
		for(int i = 0; i < N; i++) {
			cards[i] = sc.nextInt();
		}
		int ans = 0; // M에 가까운 카드의 합
		
		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 temp = cards[i] + cards[j] + cards[k]; // 카드의 합
					if(temp <= M && Math.abs(temp-M) < Math.abs(ans-M)) { // M을 넘지 않으면서 차가 작을 때
						ans = temp;
					}
				}
			}
		}
		System.out.printf("%d", ans);
	}
}

 

실행 결과

 

4. 회고

1) M 을 넘지 않기 때문에 M 이하로 구해야 함

2) 절대값을 이용하여 M 과의 차를 비교

 

5. Github

https://github.com/iihye/Algorithm/blob/main/Baekjoon/b2798.java

 

728x90
Comments