728x90
문제

입/출력

아이디어
단순히 세장의 카드를 골라서 최대값보다 크면 제외 하는 식으로 찾으면 될 것 같다고 판단.
테스트코드
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
int maxNum = sc.nextInt();
sc.nextLine();
String v = sc.nextLine();
String[] s = v.split(" ");
Integer[] nums = new Integer[s.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.parseInt(s[i]);
}
Arrays.sort(nums, Collections.reverseOrder());
solution(nums, 0, 0, maxNum, 0);
System.out.println(answer);
}
public static void solution(Integer[] array, int idx, int curCount, int maxNum, int sum) {
// 종료
if (curCount == 3) {
if (sum >= answer && maxNum >= sum) {
answer = sum;
}
return;
}
if (idx == array.length) {
return;
}
// 해당 값을 고르지 않는 경우
solution(array, idx+1, curCount, maxNum, sum);
// 해당 idx를 고르는 경우
sum += array[idx];
solution(array, idx+1, curCount+1, maxNum, sum);
}
}
=> 테스트 case 두개는 통과하는데 중간에 실패함.... 반례를 찾다가 포기...
+ 문제가 "브루드 포스 (전체 탐색)" 이기 때문에 간단하게 그냥 3중 for문으로 처리하기로함...
결과코드
import java.util.Scanner;
import java.util.Arrays;
public class Main{
static int answer = -1;
public static void main(String[] args) {
int answer = 0;
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
int maxNum = sc.nextInt();
sc.nextLine();
String v = sc.nextLine();
String[] s = v.split(" ");
int[] nums = Arrays.stream(v.split(" ")).mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int k = j + 1; k < nums.length; k++) {
int sums = nums[i] + nums[j] + nums[k];
if (sums <= maxNum && answer <= sums) {
answer = sums;
}
}
}
}
System.out.println(answer);
}
}
다시 한번 느끼지만 문제를 어렵게 볼 필요는 없을 것 같다...
728x90
반응형
LIST
'Etc > 알고리즘' 카테고리의 다른 글
| [백준] 19532 (0) | 2024.06.18 |
|---|---|
| [백준] 2231 (0) | 2024.06.18 |
| [백준] 24262 (0) | 2024.06.11 |
| [백준] 11005 (0) | 2024.06.04 |
| [백준] 2745 (0) | 2024.06.03 |