카드와 자연수 M이 주어졌을 때, 카드 3장을 골라 M을 초과하지 않는 제일 가까운 수를 구하는 프로그램 - 브루트 포스 알고리즘 |
<구현 순서>
- 카드 수와 자연수 M 입력
- 카드 번호 입력
- 3개씩 뽑을 수 있는 조합을 검사하며 max_sum 구하기 [ 조건: max_sum <= M ]
- max_sum 출력
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Step1. Enter the number of cards and M
int num = sc.nextInt();
int M = sc.nextInt();
int[] card = new int[num];
//Step2. Enter the card number
for(int i =0;i <num;i++)
card[i]=sc.nextInt();
//Step3. Find max_sum
int max_sum = 0, sum;
for(int one=0; one < num -2; one++)
for(int two= one+1; two < num -1; two++)
for(int three= two+1; three < num; three++){
sum = card[one] + card[two] + card[three];
if(sum <= M && max_sum < sum){
max_sum = sum;
if(max_sum == M){
System.out.println(max_sum);
return;
}
}
}
//Step4. Print result
System.out.println(max_sum);
}
}
'알고리즘' 카테고리의 다른 글
[알고리즘] Counting sort (+ 백준 10989) (0) | 2021.06.21 |
---|---|
[백준] 1436 : 영화감독 숌 <JAVA> (0) | 2021.01.14 |
[백준] 2231 : 분해합 <JAVA> (0) | 2021.01.13 |
[백준] 7568 : 덩치 <JAVA> (0) | 2021.01.12 |
[알고리즘] Brute force (브루트 포스) (0) | 2021.01.10 |