μ΅œλŒ€ 1 λΆ„ μ†Œμš”

πŸ“ [B2_2798] λΈ”λž™μž­

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;


public class Main {
    static StringTokenizer st;
    static int N,M;
    static int[] arr;
    static int[] cal;
    static int sum;
    static int max = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        st = new StringTokenizer(br.readLine(), " ");
        // μΉ΄λ“œμ˜ 개수
        N = Integer.parseInt(st.nextToken());

        // 숫자 M
        M = Integer.parseInt(st.nextToken());


        // μΉ΄λ“œ μž…λ ₯
         arr = new int[N];

         // 계산 λ°°μ—΄
         cal = new int[3];

        st = new StringTokenizer(br.readLine(), " ");
        for(int i=0; i<N; i++){
            arr[i] = Integer.parseInt(st.nextToken());
        }

        combination(0,0);
        System.out.println(max);

    }
    // μ‘°ν•© κ΅¬ν•˜κΈ°
    static void combination(int current, int idx){
        if(current == 3){
           for(int i=0; i<cal.length;i++){
               sum += cal[i];
           }

           if(sum <=M){
               max = Math.max(max, sum);
           }
           // sum μ΄ˆκΈ°ν™” !!
           sum = 0;
            return;
        }

        for(int i=idx; i<N; i++){
            cal[current] = arr[i];
            combination(current+1,i+1);
        }
    }
}

πŸ€” λ‚˜μ˜ 생각

μΉ΄λ“œ 3μž₯을 λ½‘λŠ” 과정이 μˆœμ„œλ₯Ό μƒκ΄€ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— μ‘°ν•© κ΅¬ν•˜λŠ” 식을 톡해 κ΅¬ν˜„ν•˜μ˜€λ‹€.
합이 Mμ΄ν•˜ 인 κ²ƒμ—μ„œ κ°€μž₯ 큰 값을 μ°Ύμ•„μ£Όλ©΄ 끝 !
쑰합을 κ΅¬ν•˜λŠ” ꡬ쑰만 μ•Œλ©΄ κ°„λ‹¨ν•˜λ‹€ !