[Boj] LIS 문제

김동연·2024년 2월 13일

알고리즘

목록 보기
12/12

가장 긴 증가하는 부분 수열

가장 긴 증가하는 부분 수열
Lis (Longest Increasing Subsequence)이다.

풀이

dp를 활용하여 현재 방문중인 누적 길이 합을 이전 노드를 역순으로 조회하며 조건 (현재 노드 값 보다 작은 노드 값)의 노드의 누적합이 가장 큰 것의 + 1로 저장한다.
말로 적으면 어려운거 같으니 그림으로는

순서도

코드

import java.io.*;
import java.util.*;

public class Main {

    public static void main(final String[] args) throws IOException {
        problem(new InputStreamReader(System.in));
    }

    public static void problem(final InputStreamReader isr) throws IOException {
        final BufferedReader br = new BufferedReader(isr);
        final int N = Integer.parseInt(br.readLine());
        final StringTokenizer st = new StringTokenizer(br.readLine());
        final int[] arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        final int[] dp = new int[N];
        Arrays.fill(dp,1);
        int result = 0;
        for (int i = 0; i < N; i++) {
            for (int j = i; j >= 0; j --){
                if (arr[i] > arr[j]){
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            result = Math.max(dp[i], result);
        }
        System.out.println(result);
    }
}

0개의 댓글