PS/백준

[백준/2798번/java] - 블랙잭

정코딩딩 2024. 4. 12. 18:07

 

import java.util.Scanner;

public class boj_2798 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int N = scan.nextInt();
        int M = scan.nextInt();
        int[] list = new int[N];

        for(int i = 0; i < N; i++){
            list[i] = scan.nextInt();
        }

        int first = 0;
        int second = 1;
        int third = 2;

        int result = 0;

        while(first < N-2){
            int sum = list[first] + list[second] + list[third];

            if( sum<=M && result < sum){
                result = sum;
            }
            third++;
            if(third > N-1){
                second++;
                third = second + 1;
            }
            if(second > N-2){
                first++;
                second = first +1;
                third = second +1;
            }
        }

        System.out.println(result);
    }
}

 

먼저, 코드를 짜게 된 생각부터 말해보자면

1. 사용자로부터 입력받을 숫자의 갯수인 N 을 입력받고, 가까운지 비교할 숫자인 M 을 입력받는다.

2. N 개 만큼의 방이 있는 list 를 만들어서 입력받은 숫자를 저장한다.

 

이제 중요하다! 숫자 조합이 어떤것들이 나올 수 있는지 예시를 들어서 살펴보자

만약 N 에 5가 들어오게 되면 다음과 같은 배열 인덱스가 나오게 될 것이다.

그리고 가능한 인덱스 조합을 생각해보면 위와 같다

어떤 규칙을 찾을 수 있을까????

잘보면 세번째 인덱스가 N-1 이면 두번째 인덱스를 하나 증가시키고, 두번째 인덱스가 N-2 면 첫번째 인덱스가 +1 된다!

그걸 코드로 표현한 부분이 아래와 같다

        int first = 0;
        int second = 1;
        int third = 2;

        int result = 0;

        while(first < N-2){
            int sum = list[first] + list[second] + list[third];

            if( sum<=M && result < sum){
                result = sum;
            }
            third++;
            if(third > N-1){
                second++;
                third = second + 1;
            }
            if(second > N-2){
                first++;
                second = first +1;
                third = second +1;
            }
        }

 

예시를 넣고 돌려보면 정답이 잘 나온다

끝!