-
2798 - 블랙잭알고리즘 2023. 5. 30. 19:58728x90
https://www.acmicpc.net/problem/2798
배열을 모두 돌면서 가장 큰 합이 무엇인지 확인하는 문제
3개의 숫자를 골라야 하므로 3개의 for문을 돌면서,
중복이 되지 않아야하므로, 시작과 종료조건을 조금씩 건드렸다.
모든 조건을 돌면서 가장 큰 것을 담을 수 있는 변수를 만들어 남아놨다.import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer token1 = new StringTokenizer(br.readLine()); int nums = Integer.parseInt(token1.nextToken()); int maxSum = Integer.parseInt(token1.nextToken()); StringTokenizer token2 = new StringTokenizer(br.readLine()); int[] arr = new int[nums]; for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(token2.nextToken()); } int sum; int candidate = 0; for (int i = 0; i < arr.length - 2; i++) { for (int j = i+1; j < arr.length - 1; j++) { for (int k = j + 1; k < arr.length; k++) { sum = arr[i] + arr[j] + arr[k]; if(sum <= maxSum){ candidate = Math.max(sum, candidate); } } } } System.out.println(candidate); } }
느낀점
브루트포스 문제는 모든 배열을 잘 돌아갈 수 있게끔해주는 작업이 필요했다.
그리고 내가 원하는 조건의 값을 저장할 변수를 설정해주면 끝나는 문제.
'알고리즘' 카테고리의 다른 글
숫자야구 (0) 2023.06.15 11866 - 요세푸스 문제 0 (0) 2023.05.30 11279 - 최대 힙 (0) 2023.05.30 4949 - 균형잡힌 세상 (0) 2023.05.30 9012 - 괄호 (0) 2023.05.26