• 생각

일전에 이런 문제를 많이 풀었는데, 푸는 방법은 다양하게있다.

1. LIS 알고리즘(dp보다 빠름) - 가장 긴 증가하는 부분 수열 2 (비슷한 문제를 LIS 알고리즘으로 푼 코드이다.)

2. DP - 가장 긴 증가하는 부분 수열 이전에 비슷한 문제를 DP 알고리즘으로 푼 코드이다.

3. 완전탐색 - 너무 오래걸린다. 시간초과 뜰 확률이 높음.

 

  • 코드

정답 코드 : DP로 구현한 코드이다.

 

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

public class Main {
	static int N;
	static int[] array, dp;

	public static void main(String[] args) throws Exception {
		SetData();
		System.out.println(DP());
	}

	private static void SetData() throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		N = Integer.parseInt(br.readLine());
		
		dp = new int[N];
		array = new int[N];
		
		StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            array[i] = Integer.parseInt(st.nextToken());
        }
		
	}
	
	private static int DP() {
        int max = 1;
        for (int i = 0; i < N; i++) {
        	if (dp[i] == 0) 
        		dp[i] = array[i];
        	for (int j = 0; j < i; j++) {
        		if (array[i] > array[j]) 
        			dp[i] = Math.max(dp[i], dp[j]+array[i]);
        	}
            if(max<dp[i])
            	max=dp[i];
        }

        return max;
	}
}

+ Recent posts