|
| 1 | +package BOJ; |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.util.StringTokenizer; |
| 6 | + |
| 7 | +public class 2798 { |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + |
| 10 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + StringTokenizer st = new StringTokenizer(br.readLine(), " "); |
| 12 | + |
| 13 | + int N = Integer.parseInt(st.nextToken()); |
| 14 | + int M = Integer.parseInt(st.nextToken()); |
| 15 | + |
| 16 | + int[] arr = new int[N]; |
| 17 | + |
| 18 | + st = new StringTokenizer(br.readLine(), " "); |
| 19 | + for (int i = 0; i < N; i++) { |
| 20 | + arr[i] = Integer.parseInt(st.nextToken()); |
| 21 | + } |
| 22 | + |
| 23 | + int result = search(arr, N, M); |
| 24 | + System.out.println(result); |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | + // 탐색 |
| 29 | + static int search(int[] arr, int N, int M) { |
| 30 | + int result = 0; |
| 31 | + |
| 32 | + // 3개를 고르기 때문에 첫번째 카드는 N - 2 까지만 순회 |
| 33 | + for (int i = 0; i < N - 2; i++) { |
| 34 | + |
| 35 | + // 두 번째 카드는 첫 번째 카드 다음부터 N - 1 까지만 순회 |
| 36 | + for (int j = i + 1; j < N - 1; j++) { |
| 37 | + |
| 38 | + // 세 번째 카드는 두 번째 카드 다음부터 N 까지 순회 |
| 39 | + for (int k = j + 1; k < N; k++) { |
| 40 | + |
| 41 | + // 3개 카드의 합 변수 temp |
| 42 | + int temp = arr[i] + arr[j] + arr[k]; |
| 43 | + |
| 44 | + // M과 세 카드의 합이 같다면 temp return 및 종료 |
| 45 | + if (M == temp) { |
| 46 | + return temp; |
| 47 | + } |
| 48 | + |
| 49 | + // 세 카드의 합이 이전 합보다 크면서 M 보다 작을 경우 result 갱신 |
| 50 | + if(result < temp && temp < M) { |
| 51 | + result = temp; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + // 모든 순회를 마치면 result 리턴 |
| 58 | + return result; |
| 59 | + } |
| 60 | +} |
0 commit comments