곽로그

[백준 11052, Java] 카드 구매하기 본문

알고리즘/백준

[백준 11052, Java] 카드 구매하기

일도이동 2020. 12. 7. 23:48
반응형

문제

www.acmicpc.net/problem/11052

 

11052번: 카드 구매하기

첫째 줄에 민규가 구매하려고 하는 카드의 개수 N이 주어진다. (1 ≤ N ≤ 1,000) 둘째 줄에는 Pi가 P1부터 PN까지 순서대로 주어진다. (1 ≤ Pi ≤ 10,000)

www.acmicpc.net

 

풀이

 f(n)을 n개의 카드를 구매할 때의 최대 가격이라고 정의하자. 이 경우 f(n) = MAX( f(n-k) + prices[k] ) ( 1<= k <= n) 이다. 따라서 for문을 이용하여 memo[n]에 f(n)의 값을 기록하면 된다. 

 

코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Main {
    public static int N;
    public static int[] prices;
    public static int[] memo;
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st;

        N = Integer.parseInt(br.readLine());
        prices = new int[N+1];
        memo = new int[N+1];

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

        /*
            f(n) : n개의 카드를 구매할 때의 최대 가격
            f(n) = Max(f(n-k)+prices[k]) (1<=k<=n)
         */
        calculateMaxPrice(N);
        int result = getMaxPrice(N);
        bw.write(String.valueOf(result));
        bw.flush();

    }
    public static void calculateMaxPrice(int n){
        for(int i = 1 ; i <=n; i++){
            memo[i] = prices[i];
            for(int j = 1; j< i ; j++){
                int tempPrice = memo[i-j] + prices[j];
                if(tempPrice> memo[i]) memo[i] = tempPrice;
            }
        }
    }
    public static int getMaxPrice(int n){
        return memo[n];
    }
}

반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 156630 , Java] N과 M (9)  (0) 2020.12.11
[백준 15656, Java] N과 M (7)  (0) 2020.12.10
[백준 1912, Java] 연속합  (0) 2020.12.07
[백준 1748, Java] 수 이어 쓰기1  (0) 2020.12.01
[백준 6064, Java] 카잉달력  (0) 2020.11.30
Comments