알고리즘

백준 2156번 포도주 시식 (JAVA)

박카스마시며코딩 2023. 7. 25. 13:26

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

 

2156번: 포도주 시식

효주는 포도주 시식회에 갔다. 그 곳에 갔더니, 테이블 위에 다양한 포도주가 들어있는 포도주 잔이 일렬로 놓여 있었다. 효주는 포도주 시식을 하려고 하는데, 여기에는 다음과 같은 두 가지 규

www.acmicpc.net

 

저는  DP를 이용하여 문제를 해결하였습니다.

저는 이전에 몇 개의 포도주를 연속으로 먹었고 그에 해당되는 값에서 최대값이 몇인지를 DP에 저장하여 문제를 해결하였습니다.

 

package BOJ.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.function.Function;

public class BOJ_2156 {
    private static final int NOT_VALID = -1;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(br.readLine());
        int[] input = new int[n];
        int[][] dp = new int[n][3];
        for(int i = 0 ; i < n ; i++){
            input[i] = stoi.apply(br.readLine());
            Arrays.fill(dp[i],NOT_VALID);
        }
        int result = cal(0,0,input,n,dp);
        System.out.println(result);
    }

    private static int cal(int depth, int cnt, int[] input,int n,int[][] dp) {
        if(depth == n){
            return 0;
        }
        if(dp[depth][cnt] != NOT_VALID){
            return dp[depth][cnt];
        }
        int result = 0;
        if(cnt < 2){
            result = Math.max(result,cal(depth+1,cnt+1,input,n,dp)+input[depth]);
        }
        result = Math.max(result,cal(depth+1,0,input,n,dp));
        dp[depth][cnt] = result;
        return result;
    }
}