Repository navigation
Expand file tree
/
Copy path2798
More file actions
63 lines (46 loc) · 1.98 KB
/
Copy path2798
File metadata and controls
63 lines (46 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
// 브루트 포스 문제
/* 모든 경우의 수를 대입해봐야합니다. 즉, 일명 노가다 문제입니다.
해당 알고리즘 같은경우 완전탐색 알고리즘을 짜야합니다. */
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] arr = new int[N];
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int result = search(arr, N, M);
System.out.println(result);
}
// 탐색
static int search(int[] arr, int N, int M) {
int result = 0;
// 3개를 고르기 때문에 첫번째 카드는 N - 2 까지만 순회
for (int i = 0; i < N - 2; i++) {
// 두 번째 카드는 첫 번째 카드 다음부터 N - 1 까지만 순회
for (int j = i + 1; j < N - 1; j++) {
// 세 번째 카드는 두 번째 카드 다음부터 N 까지 순회
for (int k = j + 1; k < N; k++) {
// 3개 카드의 합 변수 temp
int temp = arr[i] + arr[j] + arr[k];
// M과 세 카드의 합이 같다면 temp return 및 종료
if (M == temp) {
return temp;
}
// 세 카드의 합이 이전 합보다 크면서 M 보다 작을 경우 result 갱신
if(result < temp && temp < M) {
result = temp;
}
}
}
}
// 모든 반복 끝나면 return
return result;
}
}