728x90
문제 : https://www.acmicpc.net/problem/2798
2798번: 블랙잭
첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장
www.acmicpc.net
3중 for문을 이용하여 풀이하면 된다.
다만, for 문을 작성할 때,
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++)
이와 같이 첫번째 for 문은 i=0 부터 N-2 까지,
두번째는 j = i+1 부터 N-1까지,
세번째는 k=j+1 부터 N까지 로 설정해주어야 중복으로 더해지지 않는다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int [] card = new int[N];
int sum=0;
List<Integer> list = new ArrayList<>();
for (int i=0;i<N;i++) {
card[i]=sc.nextInt();
}
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++){
sum=card[i]+card[j]+card[k];
if (sum<=M){
list.add(sum);
}
sum=0;
}
}
}
Collections.sort(list, Collections.reverseOrder());
System.out.println(list.get(0));
}
}
728x90