📖 [백준알고리즘 풀이] Q.11052 카드 구매하기

📖 문제

https://www.acmicpc.net/problem/11052

🔍 접근법

n개의 카드를 구매하는데

가장 비싼 가격을 주고 구매해야합니다.

n번째 카드팩들은 n개의 카드들이 들어있습니다.

n개의 카드를 구매할때

n번째의 카드팩만을 구매하는 경우

다른 카드팩과 섞어 구매하는 경우 모두를 비교하기 위해

2중 for문으로 비교를 하였습니다.

💻 코드

package problem.dynamic.Q11052;
import java.io.*;

public class Main_11052 {
    public static int n;
    public static int[] d;
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int cards[] = input();
        int answer = solve(cards);
        bw.write(Integer.toString(answer));
        bw.flush();
        bw.close();
    }
    public static int solve(int[] cards){
        for(int i=1; i<=n; i++){
            for(int j=1; j<=i; j++) {
                d[i] = Math.max(d[i] , d[i-j] + cards[j-1]);
            }
        }
        return d[n];
    }

    public static int[] input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        int cards[] = new int [n];
        d = new int [n+1];
        String temp[] = br.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            cards[i] = Integer.parseInt(temp[i]);
        }
        br.close();
        return cards;
    }
}


Written on April 28, 2020