가장 긴 증가하는 부분 수열

Huisu·2023년 10월 26일
0

Coding Test Practice

목록 보기
54/98
post-thumbnail

문제

11053번: 가장 긴 증가하는 부분 수열

문제 설명

수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오.

예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {1020, 10, 30, 20, 50} 이고, 길이는 4이다.

제한 사항

첫째 줄에 수열 A의 크기 N (1 ≤ N ≤ 1,000)이 주어진다.

둘째 줄에는 수열 A를 이루고 있는 Ai가 주어진다. (1 ≤ Ai ≤ 1,000)

입출력 예

입력출력
6
10 20 10 30 20 504

아이디어

DP인데.. 좀 헤맷다

제출 코드


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

public class two11053 {
    private static int sequenceLength;
    private static int[] sequence;
    private static int[] dp;
    private static int result;
    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        sequenceLength = Integer.parseInt(reader.readLine());
        sequence = new int[sequenceLength];
        dp = new int[sequenceLength];

        StringTokenizer sequenceToken = new StringTokenizer(reader.readLine());
        for (int i = 0; i < sequenceLength; i++) {
            sequence[i] = Integer.parseInt(sequenceToken.nextToken());
        }

        dp[0] = 1;
        result = 1;
        for (int i = 1; i < sequenceLength; i++) {
            int max = 0;
            for (int j = i - 1; j >= 0 ; j--) {
                if (sequence[i] > sequence[j] && dp[j] > max) {
                    max = dp[j];
                    dp[i] = max + 1;
                    result = Math.max(result, dp[i]);
                }
            }
            if (max == 0) {
                dp[i] = 1;
            }
            result = Math.max(result, max);
        }
        System.out.println(result);
    }

    public static void main(String[] args) throws IOException {
        new two11053().solution();
    }
}

0개의 댓글