백준/동적 계획법

[백준] 11053 - 가장 긴 증가하는 수열 [JAVA]

odong2 2024. 4. 29. 17:31

 

코드(Bottom-up)

import org.w3c.dom.ls.LSOutput;

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

public class Main {

    static Integer[] dp;
    static int[] arr;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        dp = new Integer[N];
        arr = new int[N];

        StringTokenizer st = new StringTokenizer(br.readLine());

        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        for (int i = 0; i < N; i++) {
            dp[i] = 1;

            // 0 ~ i 이전 원소 탐색
            for (int j = 0; j < i; j++) {

                if (arr[j] < arr[i] && dp[i] < dp[j] + 1) {
                    dp[i] = dp[j] + 1;
                }
            }
        }

        int max = -1;

        for (int i : dp) {
            max = max < i ? i : max;
        }
        System.out.println(max);
    }

}

 

 

코드(Top-down)

import org.w3c.dom.ls.LSOutput;

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

public class Main {

    static Integer[] dp;
    static int[] arr;

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        dp = new Integer[N];
        arr = new int[N];

        StringTokenizer st = new StringTokenizer(br.readLine());

        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        // 0 ~ N - 1 까지 모든 부분 수열 탐색
        for (int i = 0; i < N; i++) {
            solution(i);
        }
        // 최댓값
        int max = dp[0];
    

        for (int i = 1; i < N; i++) {
            max = Math.max(max, dp[i]);
        }

        System.out.println(max);
    }

    static int solution(int n) {

        if (dp[n] == null) {
            dp[n] = 1; // 1로 초기화

            for (int i = n - 1; i >= 0; i--) {
                // 이전 값 대소 비교
                if (arr[i] < arr[n]) {
                    dp[n] = Math.max(dp[n], solution(i) + 1);
                }
            }
        }
        return dp[n];
    }

}